Trying to copy a char *str
to char c[]
but getting segmentation fault or invalid initializer error.
Why is this code is giving me a seg fault?
char *token = "some random string";
char c[80];
strcpy( c, token);
strncpy(c, token, sizeof c - 1);
c[79] = '\0';
char *broken = strtok(c, "#");
Edited: Thanks for adding the code.
Perhaps the segfault occurs here:
sizeof has a the same precedence as '-' from right to left, so it is probably processed as :
instead of
which is probably what you wanted
(reference: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence)
use strncpy to be sure to not copy more charachters than the char[] can contains
Edit: Code added to question
Viewing your code the segmentation fault could be by the line
The problem is if token length is bigger than c length then memory is filled out of the c var and that cause troubles.
It's been a while since i coded in c/c++, but c[80] is probably allocated on the stack. If you use char *c and strdup or similiar you get it allocated on the heap where strtok can access it.
Try something like this.
char c[] must have some size;
for example
// that set up table c to c[19]; You can allocate it directly at the begginign of Your program;
char c[i] is the pointer so You don't need to copy anything; char c[19] ; c = "example init string"; // now &c[0] points the same address;
Copy can be done wiht
but MS force You to use secure function:
use
strncpy()
rather thanstrcpy()