【发布时间】:2013-12-04 06:42:25
【问题描述】:
我必须分配一个包含 1000 个指向字符串的指针的数组,从标准输入读取每个字符串,然后将每行 strdup 读入数组。我做了以下事情:
char *array[1000];
int index = 0;
for (int i = 0; i < 1000; i++) {
scanf("%s", &array[i]);
strdup(array[i]);
}
我不确定这是否是正确的做法??
编辑:
所以,我需要在每行末尾插入一个空字符的换行符,我需要使用 strlen 函数来完成。我有以下内容:
// 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
请指教!
【问题讨论】:
-
我很好奇你有没有试过这个?
-
scanf("%s" ...)不是读取数据行的好方法(除非您的行从未有空格)。fgets()可能是更好的选择,或者getline()如果您可以使用该非标准(但常见)的库函数。 -
@MichaelBurr 我如何在每行末尾插入换行符并带有'\0',并且如果没有换行符不会出错?我不知道该怎么做。
标签: c