Help:Assign value dynamically

Dears,

I have series issue.i have array of pointers and when i tried to assign values dynamically all array items have the same value which is last value.

Please help


char* list[];
int DynamicDemo(void)

{

int h = 0;

int size = 6; // dynamic size

char* item[size];

for (h = 0; h < size; h++)

{
if (h == size - 1)

// last element to set to NULL

item[h] = NULL;

else

// just to allocate string to stack

item[h] = "item ()";


//sprintf((char *)item,"item %d",h);

Rprintf("item [%d]=%s\r\n", h, item[h]);

list[h] = (char*) malloc(sizeof(char) * strlen(item[h]));

sprintf(item[h], "%s (%d)", "item", h);

list[h] = (char*) item[h];

Rprintf("list[%d]=%s,item= %s \r\n", h, list[h], item[h]);
}

//all pointers in array have the same value

for (h = 0; h < size; h++)

{
Rprintf("list[%d]=%s,item= %s \r\n", h, list[h], item[h]);
}

however if item array was statically created i have no problem at all
char* item[]={"item 1",
"item 2",
"item 3",
"item 4",
"item 5",
NULL};


Please assist
Thank you

Thank you
1
2
3
// just to allocate string to stack
item[h] = "item ()";
sprintf(item[h], "%s (%d)", "item", h);

http://stackoverflow.com/questions/349025/is-a-string-literal-in-c-created-in-static-memory
An string literal is a const char * you cannot modify it.

In the first for loop the output of item[h] from 0 to 4=item(0),item(1),item(2),item(3) and item(4)

In the second for loop,The output of item[h] from 0 to 4 = item(4)

Please help me how to make it modified?
Topic archived. No new replies allowed.