我正在使用以下代码将标准输入存储到一个数组中。我最终收到大量警告和段错误。
while(fgets(str, 256, stdin)){
size_t count = 0;
char** arr = NULL;
char* token = NULL;
char* delim = ' ';
for(int i=0; i < strlen(str); i++)
if (isspace(str[i])) count++;
count++;
arr = malloc(sizeof(char*) * (count));
for(int i=0; i <= count; i++){
token = strtok(str, delim);
arr[i] = token;
}
for (int i = 0; i < count; ++i)
{
printf("%s\n", arr[i]);
}
//if(strncasecmp(str, "quit", 4) == 0) break;
free(arr);
}
我对编译中的这个警告有点困惑
c:34:12: warning: incompatible integer to pointer conversion initializing 'char *' with an expression of type 'int'
[-Wint-conversion]
char* delim = ' ';
^ ~~~
当然,最后当我运行它时,我遇到了段错误。
admin 123 tyu
Segmentation fault: 11
我在这里做错了什么。
最佳答案
我在这里注意到第一个问题。 这可不好。
for(int i=0; i <= count; i++){
token = strtok(str, delim);
arr[i] = token;
}
将其替换为以下内容:
token = strtok(str, delim);
while(token){
arr[i] = token;
token = strtok(NULL, delim);
}
strtok
的引用手册说你在str
上使用它一次,其余使用NULL
连续分割字符串。看strtok()
手册页和给定的简单用法示例。
第二点是 delim
必须是 C 字符串,所以在您的情况下 char*
类型将是 delim = ""
不是 delim = ' '
。理想情况下,它也应该是 const char *delim = "";
。
关于c - 将来自标准输入的输入存储在 C 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429585/