问题
I think it's the very first strtok call that's failing. It's been a while since I've written C and I'm at a loss. Thanks very much.
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char *str = "one|two|three";
char *tok = strtok(str, "|");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, "|");
}
return 0;
}
回答1:
String literals should be assigned to a const char*, as modifying them is undefined behaviour. I'm pretty sure that strtok modifies it's argument, which would explain the bad things that you see.
回答2:
There are 2 problems:
Make
str
of typechar[]
. GCC gives the warningfoo.cpp:5: warning: deprecated conversion from string constant to ‘char*’
which indicates this is a problematic line.Your second
strtok()
call should haveNULL
as its first argument. See the docs.
The resulting working code is:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char str[] = "one|two|three";
char *tok = strtok(str, "|");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, "|");
}
return 0;
}
which outputs
one
two
three
回答3:
I'm not sure what a "bus" error is, but the first argument to strtok() within the loop should be NULL if you want to continue parsing the same string.
Otherwise, you keep starting from the beginning of the same string, which has been modified, by the way, after the first call to strtok().
来源:https://stackoverflow.com/questions/4480552/why-does-the-following-c-program-give-a-bus-error