为什么下面的代码不能按预期工作

问题描述 投票:0回答:0

我有一个字符串,我想把它拆分成单词。当传递的字符串以空格结尾时代码有效,否则无效

代码:

void form_rule2(char * str)
{
    int num_words=0;
    char word[20];
    while(sscanf(str,"%s",word)==1)
    {
        num_words++;
        printf("%s\n",word);

        str+=strlen(word)+1;
    }

}

void main()
{
    form_rule2("abcd efgh! ijkl mnop");
}

我得到的输出是:

abcd 呃! ijkl mnop P

很明显'P'是多余的,其他测试用例的情况也类似,最后给出随机字符。

我想了解这里发生了什么,以某种方式涉及 NULL 终止字符。

如果重要的话,我在带有 x86-64 处理器的 Linux 上使用 gcc 编译器。

谢谢。

c substring c-strings
© www.soinside.com 2019 - 2024. All rights reserved.