c - 字符串数组实现返回段错误

标签 c arrays string segmentation-fault

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/

相关文章:

python - 检查一个字符串是否包含 Python 列表中的任一字符串

c++ - 使用 System V 信号量创建聚集/屏障函数

arrays - 根据用户在 Swift 中的选择从数组加载自定义单元格值

arrays - bash + for 循环 + 输出索引号和元素

r - 测试字符是否在字符串中

c++ - 字符串下标超出范围错误

c++ - std::cout 的简约重新实现

c - 如何在 C 中的整数数组中选择(有效)随机相邻点?

C 链表在指针传递时被修改

java - 程序给出数字而不是*