c - 指向结构的指针数组

标签 c

我有一个这样的结构

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/

相关文章:

c - 将 const char** 传递给函数 - 如何构建 char**?

curl 在第二遍时不抓取页面而是返回空字符串?

C - 单词数组

c - 这段代码给出了 head->next = NULL,尽管它不应该

c - 在优化和不优化的情况下访问越界索引

c - 如何定义一个函数,该函数接受用户的输入并将其存储到程序中进一步使用的变量中?

使用 gcc-4.9 将矢量化检查为简单示例

c - 我试图确定 C 是否可以在其预编译器中使用 '!'

c - 通过计算汇编指令来测量 CPU 速度

C 图灵机无限循环