Home > front end >  why won't VScode compile the function strtok proprely?
why won't VScode compile the function strtok proprely?

Time:11-16

I started working on VS Ccode recently and I want to use the function strtok() for my project but it won't compile run properly. I tried compiling this function in an online compiler and it works so apparently the issue is with VScode.

Has anyone ever encountered this issue? And does anyone have a solution to my problem?

#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;
}

The function is stuck on an infinite loop when I compile it with VScode. I know the issue is with the line "dividedline = strtok(NULL,s);" and especially with the NULL, but I can't figure out what's wrong.

CodePudding user response:

Your problem is the line:

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

You don't know what the initial value of i is. You should have written:

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

A more defensive style of programming would use:

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

Your loop could still take a long time if i was initialized negative, but would stop immediately if i was positive and bigger than 3. The < idiom is normal in C.

  • Related