Hi,
In a program I'm writing I am attempting to create an array of Strings which is populated with values from a for loop.
I've created the toy program below to illustrate the issue I'm having:
I intended the above code to create a new String for every element of the char pointer array and to print out the values 0 ... 9. Currently it prints out all 9's.Code:void fillPArray() { char *pArray[10]; int i; for (i=0;i < 10;i++) { char aString[10]; sprintf(aString, "%d", i); pArray[i] = aString; } for (i=0;i < 10;i++) { printf("%s\n", pArray[i]); } }
Could it be that the char array aString is being reinitialised on each entry of the loop, allocating the same memory; hence making all the pointers point to the same memory location?
Whatever the issue is I can't figure out how to handle this properly.
Any idea what's going wrong here?
Thanks,
Danny