cstringstrtok

Access violation In C Trying to Use strtok in a function


I am trying to pass a string to a function and tokenize the string, but it gives me an access violation error when it tries to execute strtok.

int main(void) {
char String1[100];
// note: I read data into the string from a text file, but I'm not showing the code for it here
tokenize(String1);

return 0;
}

void tokenize(char data[]) {
    strtok(data, ','); // gives me an access violation error
}

When I used strtok in main, it works, but not when I pass it to the function.


Solution

  • If your compiler is not giving you plenty of warnings about this code, please enable more warnings.

    1. You need to #include <string.h> to get the prototype for strtok().
    2. You either need a prototype for tokenize(), or more simply, just move its definition above main().
    3. (Where your actual bug is) The second parameter of strtok() should be a char *, not a char. So change ',' to ",".