Reputation: 105
I would like break up a string sequence by " "
and stick it into an array. This is the code that I have but does not work:
int main(void) {
char s[] = "this is a string";
char* x = NULL;
unsigned int i = 0;
for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " ")) {
x[i] = *p;
puts(x[i]);
i++;
}
return 0;
}
It gives me the following error: error:
array initializer must be an initializer list
I am at a loss on how to accomplish this in C. So I would like x[0] = "this"
,
x[1] = "is"
and so on. Any help would be appreciated, I have searched for the answer and read tutorials but still cant come up with the right answer. Any help would be greatly appreciated. Thanks!
Upvotes: 2
Views: 85
Reputation: 726489
There are two problems with your code:
realloc
, or pre-allocating sufficient space, and using some of it.strtok
for future use. In general, this is not safe, because tokens point to the original string. It is safer to copy each token into separate space.Here is how your code would look with pre-allocated space for 100 tokens:
int main(void) {
char s[] = "this is a string";
char* x[100];
unsigned int i = 0;
for (char *p = strtok(s," "); i != 100 && p != NULL; p = strtok(NULL, " ")) {
x[i] = malloc(strlen(p)+1);
strcpy(x[i], p);
puts(x[i]);
i++;
}
// Now you need to free the strings
for (unsigned int j = 0 ; j != i ; j++) {
free(x[j]);
}
return 0;
}
If you are certain that there would be no modifications done to s
, you could store tokens directly, too:
int main(void) {
char s[] = "this is a string";
char* x[100];
unsigned int i = 0;
for (char *p = strtok(s," "); i != 100 && p != NULL; p = strtok(NULL, " ")) {
x[i] = p;
puts(x[i]);
i++;
}
return 0;
}
Upvotes: 6