I have a struct like so
typedef struct person {
int id;
char name[20];
} Person;
Then, outside of the function, I have a pointer array of pointers to these structs, like so
Person **people;
Then in the function I am adding people to the array like so (in a loop)
Person person;
for (i = 0; i < 50; i++)
{
person.id = i;
person.name = nameArray[i];
people[i] = &person;
}
person is being added to the people array but when (in VS2010) I go to the Watch screen and type people, 50
I just see the same person in every slot as if when adding the next person, it changes all previous as well. What am I doing wrong here?
Also, to retrieve a certain person’s name, is this the right syntax?
people[0] -> name; Or is it people[0][0].name?
Thanks!
What do you expect? You are making all the pointers point to the same
Person. And whenpersongoes out of scope, all the pointers in your array (which are all the same) will be invalid and point to a deallocated block of memory. You have to usemallocin each iteration of the loop to allocate dynamic storage and create aPersonthat won’t go away till youfreeit:Alternatively, you could have an array of
Persons instead ofPerson*s and what you are doing would work:And with that way you don’t have to
freeanything.