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.
CodePudding user response:
You should consult man strtok for more detail. And it's advisable to use strtok_r
instead of strtok
.
#include <stdio.h>
#include <string.h>
void tokenize(char data[]) {
char *token = data;
while (1) {
token = strtok(token, ",");
if (!token) {
break;
}
printf("token : %s\n", token);
token = NULL;
}
}
int main(void) {
char String1[] = "a,b,c,d,e,f,g";
// 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;
}
CodePudding user response:
If your compiler is not giving you plenty of warnings about this code, please enable more warnings.
- You need to
#include <string.h>
to get the prototype forstrtok()
. - You either need a prototype for
tokenize()
, or more simply, just move its definition abovemain()
. - (Where your actual bug is) The second parameter of
strtok()
should be achar *
, not achar
. So change','
to","
.