How this works: char *array[10]
is an array of 10 char *
pointers (basically 10 same things as token
).
token = "testing"
creates static space somewhere in your program's memory at build time, and puts "testing" there. Then in run time, it puts address to that static "testing" to token
.
array[0] = "again"
does basically the same thing.
Then, strcat(array[0], token)
takes address in array[0]
, and tries to add token
's content to string at that address. Which gives you segfault, since array[0]
points to read-only data segment in your memory.
How to do this properly:
char * initial = "first"; // pointer to static "first" string
char * second = "another"; // another one
char string[20]; // local array of 20 bytes
strcpy(string, initial); // copies first string into your read-write memory
strcat(string, second); // adds the second string there
Actually, if you don't want to shoot yourself in the foot, the better way to do something like the last two lines is:
snprintf(string, sizeof(string), "%s%s", initial, second);
snprintf
then makes sure that you don't use more than 20 bytes of string
. strcat
and strcpy
would happily go over the limit into invalid memory, and cause another run-time segfault or something worse (think security exploits) if the copied string were longer then the destination space.