arrays and strings in c -


i break string sequence " " , stick array. code have not work:

int main(void) {     char s[] = "this string";     char* x = null;     unsigned int = 0;      (char *p = strtok(s," "); p != null; p = strtok(null, " ")) {        x[i] = *p;        puts(x[i]);        i++;     }     return 0; } 

it gives me following error: error:

array initializer must initializer list

i @ loss on how accomplish in c. x[0] = "this", x[1] = "is" , on. appreciated, have searched answer , read tutorials still cant come right answer. appreciated. thanks!

there 2 problems code:

  • you trying grow array go. not possible in c without using dynamic allocation realloc, or pre-allocating sufficient space, , using of it.
  • you trying store results of strtok future use. in general, not safe, because tokens point original string. safer copy each token separate space.

here how code pre-allocated space 100 tokens:

int main(void) {     char s[] = "this string";     char* x[100];     unsigned int = 0;      (char *p = strtok(s," "); != 100 && p != null; p = strtok(null, " ")) {        x[i] = malloc(strlen(p)+1);        strcpy(x[i], p);        puts(x[i]);        i++;     }     // need free strings     (unsigned int j = 0 ; j != ; j++) {         free(x[j]);     }     return 0; } 

demo.

if there no modifications done s, store tokens directly, too:

int main(void) {     char s[] = "this string";     char* x[100];     unsigned int = 0;      (char *p = strtok(s," "); != 100 && p != null; p = strtok(null, " ")) {        x[i] = p;        puts(x[i]);        i++;     }     return 0; } 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -