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
ab then cd then ef
void sort(char* str)
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
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,
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".