0

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.

Calicore
  • 3
  • 1
  • 2
    Please [edit] and show a [mcve] with hardcoded test data. Or maybe you *should* show the code that reads the string from the file, the problem might be there, who knows. Also show the includes, they matter. And read the warnings, the compiler shows you. – Jabberwocky Jan 25 '23 at 08:24
  • 6
    The second parameter to `strtok()` should be a `char *` but you are passing a `char`. Did your compiler not tell you that? – pmacfarlane Jan 25 '23 at 08:25

2 Answers2

0

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;
}
Manthan Tilva
  • 3,135
  • 2
  • 17
  • 41
0

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 ",".
pmacfarlane
  • 3,057
  • 1
  • 7
  • 24