Ahmed M. Salah Ahmed M. Salah - 1 year ago 71
C Question

converting a string into array of pointers to characters

I am trying to write a code to convert a string into an array of pointers, each pointer points to a word in that string. when I compile the code below and print every word separately inside the first loop I get every word alright, but after the loop finishes and then I try to print each word in the array through a loop , all elements of the array are the same which is the last word in the string.

If we passed "ab cd ef" to this function, the last loop will print

ef then ef then ef

but if I print every element of the array in the first loop it will print

ab then cd then ef


void sort(char* str)
char* a[100]={NULL};
char *tStr2,*min,*temp;
int i=0,i2=0,j=0;
if(str[i]!=' ' && i!=strlen(str))
tStr2[i2]=str[i]; //copy every word separately to tStr2[]
a[j]=tStr2; //word is complete --> copy it to the array
printf("%s \n",a[j]); //print every word
i2=0; //initializes the word counter
for (i=0;a[i];i++) //loop is complete , print all array elements
printf("%s \n",*a[i]);

Answer Source

a[j]=tStr2; copies the same pointer to the various elments of a[]. So later on when code prints a[j], it refers to the text.

Code needs to save different pointers in the various a[j] elements. Perhaps as simple as the common, but non-standard, strdup().

a[j] = strdup(tStr2);

Additional code needed to free() this allocation.

An alternate approach would copy str once and replace its ' ' with '\0' and have a[j] point to the various beginning "words".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download