为什么VScode无法正确编译函数strtok?

dfty9e19  于 2022-12-03  发布在  Vscode
关注(0)|答案(1)|浏览(159)

我最近开始在VS Ccode上工作,我想在我的项目中使用函数strtok(),但是它不能正确编译运行。我试着在在线编译器中编译这个函数,它工作得很好,很明显问题是与VScode有关。
有没有人遇到过这个问题?有没有人能解决我的问题?

#include <stdio.h>
#include <string.h>

char *base(char *line){ 
    
    char *base, *dividedline;
    const char s[3] = " ";

    //get the first token
    dividedline = strtok(line,s);
    printf("%s\n", dividedline);
    //get the others
    for(int i; i!=3;i++){ 
        dividedline = strtok(NULL,s);
        printf("%s\n", dividedline);
        if(i == 2){ 
            base = dividedline;
        }
        return dividedline;
    }
    printf("finished");
    return base;

}

int main()
{
    printf("hello world \n");
    char *l;
    char str[80] = "hi  test    test";
    l = base(str);

    return 0;
}

当我用VScode编译这个函数时,它被困在一个无限循环中。“特别是NULL,但我不知道出了什么问题。

8ljdwjyq

8ljdwjyq1#

你的问题是这行字:

for(int i; i!=3;i++)

你不知道i的初始值是多少,你应该写:

for (int i = 0; i != 3; i++)

一种更具防御性的编程风格将用途:

for (int i = 0; i < 3; i++)

如果i初始化为负数,循环仍然会花费很长时间,但如果i为正数且大于3,循环就会立即停止。

相关问题