gpt4 book ai didi

c - 指向结构的指针数组

转载 作者:行者123 更新时间:2023-12-02 05:44:09 26 4
gpt4 key购买 nike

我有一个这样的结构

typedef struct person {
int id;
char name[20];
} Person;

然后,在函数之外,我有一个指向这些结构的指针数组,就像这样

Person **people;

然后在函数中我像这样(在循环中)将人添加到数组

Person person;

for (i = 0; i < 50; i++)
{
person.id = i;
person.name = nameArray[i];
people[i] = &person;
}

person 被添加到 people 数组,但是当(在 VS2010 中)我转到 Watch 屏幕并键入 people, 50我只是在每个插槽中看到相同的 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]);

或者,您可以有一个 Person 数组而不是 Person* 数组,您正在做的事情会起作用:

Person people[50];

Person person;

for (i = 0; i < 50; i++)
{
person.id = i;
person.name = nameArray[i];
people[i] = person; // make a copy
}

通过这种方式,您不必释放任何东西。

关于c - 指向结构的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9470662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com