int main(void)
{
const char* line = "This isn't working";
char* str[10];
int index = 0;
for(int i = 0; i < 10; i++)
{
int j = 0;
str[i] = malloc(10 * sizeof(char));
while(line[index] != ' ')
{
str[i][j] = line[index];
j++;
index++;
}
index++;
if(index == strlen(line) - 1)
break;
}
for(int i = 0; i < 10; i++)
{
printf("%s\n", str[i]);
}
}
我正在尝试创建一个字符串数组,我想在其中存储变量“line”中的单词。但我写的代码给出了“段错误”,请帮忙
最佳答案
在示例字符串“这不起作用”
上,您的while(line[index] != ' ')
将永远有效。在此循环之后,长度检查仅进行一次。因为它你有未定义的行为。这可能是您问题的主要原因。关于这个主题的好文章"Undefined behavior can result in time travel" 。
要修复此问题,请将 while
循环条件更改为:
int strLength = strlen(line);
while (index < strLength && line[index] != ' ')
{
// Do the job here
}
关于c - 字符串数组实现返回段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39336985/