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
for(i=0;i<3;i++) { char temp[5]; sprintf(temp,"VAL:%d",i); foo[i] = temp; }assigns a pointer to a local variable that doesn't exist anymore after the loop body finished. Didn't your compiler warn about that?