I can’t assign values to a char array in loop, doing it contains same value in every array value
for example this works
char* foo[3];
foo[0] = "mango"; foo[1] = "kiwi"; foo[2] = "banana";
int i=0; for(i=0;i<3;i++)
{
printf("%s\n",foo[i]);
}
but this doesn’t and I don’t understand why.
char* foo[3]; int i=0;
for(i=0;i<3;i++) {
char temp[5];
sprintf(temp,"VAL:%d",i);
foo[i] = temp;
}
for(i=0;i<3;i++)
{
printf("%s\n",foo[i]);
}
please help and thanks in advance
You have to remember that in C, a
char*does not actually store a string, but it stores the address of a memory location that will be treated as the first character of a string.In your first example, each element of the
fooarray holds the address of a different string-literal.In your second example, each element of the
fooarray is made to point to the local variabletemp. Although each iteration through the loop results in a separate instance oftemp, any sane compiler will place all those instances on top of each other, thus giving the results you experience.The solution is either to use a 2D array:
Or to use dynamic allocation: