strtok example on c++.com

Hello everyone!

In regards to the strtok() function example at http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  //char * str = " x1 x7 x10 x29 ";
  char str[] = " x1 x7 x10 x29 ";
  printf ("Splitting string \"%s\" into tokens:\n",str);
  char * pch = strtok (str," ");

  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ");
  }

  return 0;
}


The program runs fine using a character array, however it crashes when using a cstring!

My problem is: I'm using cstrings in my program (char *), how can I avoid a crash?
A C-string is a character array. What makes a character array a C-string is the terminating character.

As far as your problem post your code, then maybe we can see where you went wrong.

I posted the code above :)

if str is of type char [], then no problem happens. If, otherwise, str is of type char *, the program crashes.

That is why I asked for your code, how did you declare, allocate and initialize your pointer?

If you just tried "char *str = " x1 x7 x10 x29 ";" then yes the program would probably crash because you are using a const character sting and since strtok() tries to modify the string it will probably crash.

Topic archived. No new replies allowed.