C 是否将每一行标准排列到数组中?

C 是否将每一行标准排列到数组中?,c,C,我必须为字符串分配一个包含1000个指针的数组,从stdin读入每个字符串,并将每行strdup读入数组。我做了以下工作: char *array[1000]; int index = 0; for (int i = 0; i < 1000; i++) { scanf("%s", &array[i]); strdup(array[i]); } // Plug the newline where the end of // a line is

我必须为字符串分配一个包含1000个指针的数组,从stdin读入每个字符串,并将每行strdup读入数组。我做了以下工作:

char *array[1000];
 int index = 0;
 for (int i = 0; i < 1000; i++) {
      scanf("%s", &array[i]);
      strdup(array[i]);
 }
  // 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';
  }
但是我得到了以下错误:

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
请告知

char *array[1000];

 for (int i = 0; i < 1000; i++) {
      scanf("%s", &array[i]);  <-- array[i] has no memory here!!
      strdup(array[i]);    <-- array[i]=strdup(string) 
 }
char*数组[1000];
对于(int i=0;i<1000;i++){

scanf(“%s”和&array[i]);您需要一个中间数组。您不能只在此处将数据存储到未初始化的内存中
scanf(“%s”和&array[i]);

char*数组[1000];
char-buf[50];
char-buf2[50];
对于(int i=0;i<1000;i++){
scanf(“%49s”,buf);
snprintf(buf2,sizeof(buf),%s\n,buf);
数组[i]=strdup(buf2);
}
返回0;
}

这不太可能奏效。您有一个指针数组,这很好,但是您正在使用
scanf(“%s”,&array[i])读取未定义的内存,因为它实际上还没有指向任何有效的存储

相反,您需要分配一个临时缓冲区,例如

char tmp[500];
scanf("%s", tmp);
array[i] = strdup(tmp);
然后在临时缓冲区上使用
strdup
,例如

char tmp[500];
scanf("%s", tmp);
array[i] = strdup(tmp);

我很好奇您是否尝试过这种方法?
scanf(“%s”…)
不是读取数据行的好方法(除非您的行中从来没有空格)
fgets()
可能是更好的选择,或者
getline()
如果您可以使用非标准(但通用)库函数。@MichaelBurr如何在每行末尾插入换行符,并在没有换行符时不出错??我不知道该怎么做。如果没有换行符,我该如何在每行末尾插入换行符“\0”,而不出错?另一篇帖子上有人说scanf(“%s,tmp”)不读取输入行,只读取连续的非空白序列