【问题标题】:String Array implementation is returning segmentation fault字符串数组实现返回分段错误
【发布时间】:2016-09-05 20:00:04
【问题描述】:
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”中的单词。但是我写的代码给出了“分段错误”请帮忙

【问题讨论】:

  • 您没有以空值终止您的字符串。
  • ...您也没有进行循环限制以确保您的字符附加不会超出您希望获得的未经检查的分配空间。

标签: c arrays string segmentation-fault


【解决方案1】:

在示例字符串"This isn't working" 上,您的while(line[index] != ' ') 将永远有效。在此循环之后,仅进行一次长度检查。因为它,你有未定义的行为。这可能是您的问题的主要原因。关于这个主题的好文章"Undefined behavior can result in time travel"

要修复它,请将 while 循环条件更改为:

int strLength = strlen(line);
while (index < strLength && line[index] != ' ')
{
  // Do the job here
}

【讨论】:

    【解决方案2】:

    C 字符串需要以 NUL 结尾。在你的内部循环之后,你可以说str[i][j] = '\0' 来解决这个问题。

    代码至少还有一个问题:当你到line的最后一个字的时候,就没有空间来终止内循环了,所以内循环会一直运行下去,读无关的记忆,直到你碰巧在 Never Never Land 中遇到了一个太空角色。

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多