的strdup每一行入阵? [英] Strdup each line into the array?

查看:136
本文介绍了的strdup每一行入阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不分配的1000指针字符串,在从stdin每一字符串读阵列和的strdup各行成的阵列。我做了以下内容:

I have to allocate an array of 1000 pointers to character strings, read in each character string from stdin and strdup each line into the array. I did the following:

char *array[1000];
 int index = 0;
 for (int i = 0; i < 1000; i++) {
      scanf("%s", &array[i]);
      strdup(array[i]);
 }

我不知道这是不是绕了??

I'm not sure if this is the correct way of going about it??

编辑:

所以,我需要在一个空字符每一行的末尾堵塞换行,我需要使用strlen函数来做到这一点。我有以下几点:

So, I need to plug the newline at the end of each line with a null character and I need to do it using the strlen function. I have the following:

  // Plug the newline where the end of 
  // a line is equal to '0/'
  index = strlen(array) - 1;    // line 30
  if (array[index] = '\n') {    // line 31
     array[index] = '\0';
  }

但即时得到以下错误:

But Im getting the following error:

linesort.c: In function ‘main’:
linesort.c:30: warning: passing argument 1 of ‘strlen’ from incompatible pointer type
/usr/include/string.h:399: note: expected ‘const char *’ but argument is of type ‘char **’
linesort.c:31: warning: assignment makes pointer from integer without a cast
linesort.c:31: warning: suggest parentheses around assignment used as truth value

请指教!

推荐答案

您需要一个中间数组。你不能只是存储到这里未初始化的内存 scanf函数(%S,&安培;阵列[我]);

You need an intermediate array. You can't just store into uninitialized memory here scanf("%s", &array[i]);

char *array[1000];
char buf[50] ;
char buf2[50] ;

for (int i = 0; i < 1000; i++) {
    scanf("%49s", buf);
    snprintf( buf2 , sizeof( buf ) , "%s\n" , buf ) ;
    array[i] = strdup( buf2 );
}
return 0 ;
}

这篇关于的strdup每一行入阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆