Char数组应该是空的

时间:2014-03-14 08:46:30

标签: c arrays string

我试图找到两个单词之间的前缀,但似乎我所拥有的不正确。首先if(strlen(root) == 0)总是评估为0.为什么?

The longest common prefix of astrophysics and math is 0��. // <<--- why does this get printed? //

4 个答案:

答案 0 :(得分:2)

  1. 您的root包含垃圾值,您需要将其初始化 char root [256 + 1] = {0};

  2. 在你的while循环之后, root[i]='\0';

  3. 现在,试试吧。

答案 1 :(得分:2)

C中的字符串由\0字符终止。 strlen返回第一个和终结符之间的字符数。由于您正在动态构建字符串而不附加终结符,strlen将在第一个内存和内存之间返回任意数量的字符,它会遇到终结符(或者只是因为分段错误而失败) ,出于同样的原因)。

要解决此问题,您应该添加此处理:

root[0] = '\0';
while(first_word[i] == second_word[i])
{
    printf("root[%d] = %s\n", i, root);
    root[i] = first_word[i];
    root[i+1] = '\0';
    i++;
}

答案 2 :(得分:1)

你需要null-terminate root:

    while(first_word[i] == second_word[i])
    {
        /* printf("root[%d] = %s\n", i, root);   Can't print root here - it isn't null-terminataed yet */
        root[i] = first_word[i];
        i++;
    }
    root[i] = '\0';

答案 3 :(得分:0)

首先,不要在root初始化之前执行此操作:

printf("root[%d] = %s\n", i, root);

root的内容未定义,通过打印它,你让printf()打印任何垃圾值root保持,可能会偏离边界,直到找到空字节。< / p>

您的问题是您没有终止root。首先,修复循环。如果两个单词相同,则它将访问越界位置。所以,你的循环条件应该是:

while(first_word[i] == second_word[i] && first_word[i] != '\0')

然后,在循环之后放置它:

root[i] = '\0';
相关问题