Assign value to array of pointers

You’re allocating a new memory block of size sizeof(char*)*10 (which, assuming you want enough space for 10 characters, not 10 pointers, should be sizeof(char)*10), and then having each index in the item array point to a new block of memory in a loop. All is well and good until you overwrite where the item array points with the code item[h]=&x[0]. This makes every pointer in the item array point the same memory location (x). Just sprintf directly into the new memory instead. Also, because you’re dealing with strings, make sure to null terminate. Also, you need to make sure you don’t write more than 9 characters into your buffer of size 10. Also, unless using c strings is necessary, take chris’ advice and use std::string.

int h = 0;
char* item[6];

for (h = 0; h < 6; h++)
{
  item[h] = (char*)calloc(20,sizeof(char));
  sprintf(item[h], "item (%d)", h);
  printf("item= %s\n", item[h]);
}
for (h = 0; h < 6; h++)
{
  printf("item2= %s\n", item[h]);
}

Leave a Comment