tags:

views:

112

answers:

4

Hi,
the program for strtok given on http://www.opengroup.org/onlinepubs/000095399/functions/strtok.html crashes everytime..

#include <string.h>
...
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";


/* Token will point to "LINE". */
token = strtok(line, search);


/* Token will point to "TO". */
token = strtok(NULL, search);

If I use a char array for variable 'line', it works. i.e. char line[] = "LINE TO BE SEPARATED" works.

Kindly explain.

+5  A: 

strtok modifies the input string line.

char *line = "LINE TO BE SEPARATED";

In this case line points to the read-only memory. Hence, cannot be modified. You need to pass char array for strtok.

aJ
+1  A: 

aJ said what is needed. My advice is avoid that ugly & unsafe strtok. You are using C++ so go ahead with std::string. You also can use Boost http://www.boost.org/doc/libs/1_43_0/libs/libraries.htm#String & http://www.boost.org/doc/libs/1_43_0/doc/html/string_algo.html . If you want a new string classes, you may look at http://bstring.sourceforge.net/ .

Viet
+2  A: 
sbi
I smell a `std::copy` here … ;-)
Konrad Rudolph
add `#include <iostream>` and replace the `'\n'` with `<< std::endl`
James Morris
@Konrad: I can kind of guess what you're hinting at, but this `std::copy` idiom just never really appealed to me.
sbi
@James: I added the `<iostream>`, but I don't see a reason to flush `std::cout`'s buffer for every token, so I left it at `'\n'`.
sbi
@sbi: Huh? One statement in place of a loop with four statements. Granted, it’s longer but then C++ sucking at syntax is no news. Let me see if I get this right: `copy(istream_iterator<string>(iss), istream_iterator<string>(), ostream_iterator<string>(cout, "\n"));`.
Konrad Rudolph
@Konrad: I hadn't claimed my dislike to be rational. `:)`
sbi
+1  A: 

char *line is a pointer and you are pointing it to a constant string ("LINE TO BE SEPARATED"). This fails when strtok attempts to modify that string. It would be better to qualify this variable as const char *line—still wouldn't work, but might lead to a helpful warning when you try to pass it to strtok.

Meanwhile the array char line[] can be modified (it's not const) and only initialised to contain the string.

Arkku