我有一个像这样的结构
typedef struct person {
int id;
char name[20];
} Person;
Run Code Online (Sandbox Code Playgroud)
然后,在函数之外,我有一个指向这些结构的指针数组,就像这样
Person **people;
Run Code Online (Sandbox Code Playgroud)
然后在函数中我将人们添加到数组中(在循环中)
Person person;
for (i = 0; i < 50; i++)
{
person.id = i;
person.name = nameArray[i];
people[i] = &person;
}
Run Code Online (Sandbox Code Playgroud)
person正在添加到people数组但是当(在VS2010中)我进入Watch屏幕并输入people, 50
I时,只是person在每个插槽中看到相同的内容,就像添加下一个人一样,它也会改变以前的所有内容.我在这做错了什么?
另外,要检索某个人的姓名,这是正确的语法吗?
people[0] -> name; 或者是 people[0][0].name吗?
谢谢!
你能指望什么?您正在使所有指针指向相同的Person.当person超出范围时,数组中的所有指针(都是相同的)将无效并指向已释放的内存块.你必须malloc在循环的每次迭代中使用它来分配动态存储并创建一个Person不会消失的free东西:
for (i = 0; i < 50; i++)
{
Person *person = malloc(sizeof(Person));
person->id = i;
person->name = nameArray[i];
people[i] = person;
/* or:
people[i] = malloc(sizeof(Person));
people[i]->id = i;
people[i]->name = nameArray[i];
it does the same thing without the extra temporary variable
*/
}
// then when you are done using all the Person's you created...
for (i = 0; i < 50; ++i)
free(people[i]);
Run Code Online (Sandbox Code Playgroud)
或者,你可以有一个Persons而不是Person*s 的数组,你正在做的事情会起作用:
Person people[50];
Person person;
for (i = 0; i < 50; i++)
{
person.id = i;
person.name = nameArray[i];
people[i] = person; // make a copy
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,你没有free任何东西.