c-访问指向结构的指针的动态分配数组的成员



我需要有一个全局动态指针数组,我将在其中存储我的结构,因为稍后我需要遍历这个数组来列出所有存储的信息,我还需要能够从控制台读取nameagejob变量,并将它们存储在iterator数组中的person_t中。

#include <stdio.h>
#include <stdlib.h>
typedef struct Person
{
char name[30];
int age;
char job[30];
} person_t;
person_t **iterator;
int capacity = 10;
int size = 0;
int main()
{
int i;
*iterator = (person_t *)malloc(capacity * sizeof(person_t));
for (i = 0; i < capacity; ++i)
{
person_t p;
p.age = i;
*iterator[i] = p;
}
return 0;
}

编译这段代码(gcc-ansi-pedantic-Wall-Wextra(时没有收到任何错误/警告,但当我尝试运行它时,我会立即收到Segmentation fault

执行此操作时:

*iterator = (person_t *)malloc(capacity * sizeof(person_t));

您正在延迟iterator,但是作为一个文件范围指针变量,它被初始化为NULL。试图取消引用NULL指针会调用未定义的行为。

我怀疑真正想要的是一个structs数组,而不是指向structs的指针数组。在这种情况下,将iterator定义为:

person_t *iterator;

然后你这样为它分配内存:

iterator = malloc(capacity * sizeof(person_t));

然后分配给数组元素,如下所示:

iterator[i] = p;

您声明的目的是创建一个"指针的全局动态数组,我将在其中存储我的结构">。以下对代码的修改(见注释(将做到这一点:

person_t p[10] = {0};
int main()
{
int i;
// with declaration: person_t **iterator = NULL;, 
//following is all that is needed to create an array of pointers:
iterator = malloc(capacity * sizeof(person_t *));//no need to cast return of malloc


for (i = 0; i < capacity; ++i)
{
//person_t p;//moved to scope that will exist outside of main()
p[i].age = i;
iterator[i] = &p[i];//assign the address of the object to the pointer
//iterator[i] is the ith pointer in a collection of 
//pointers to be assigned to point to 
//instances of struct person_t 
}
//Once all fields are populated (to-do), the following will display the results:
for (i = 0; i < capacity; ++i)
{ 
printf("%d) Name: %s Age: %d  Job: %sn",  i, iterator[i]->name,iterator[i]->age,iterator[i]->job);
}
return 0;
}

您没有正确分配内存

首先,您需要为一个指针分配内存,该指针可以存储地址的capacity编号,即通过iterator = malloc(capacity * sizeof(person_t*));完成,然后您需要为保存每个结构元素分配内存,即iterator[i] = malloc(sizeof(person_t));

所有的malloc'd内存都应该是free'd

此外,还没有对malloc的进行错误检查,这只是留给您的练习。

int main()
{
int i;
// test data
char *names[] = {"ABC", "DEF"};
char *jobs[] = {"Accountant", "Security"};
int ages[] = {50, 60};

// first allocate memory for iterator , which can hold pointers to store iterator poniters
iterator = malloc(capacity * sizeof(person_t*)); 

for (i = 0; i < capacity; ++i)
{
// now allocate memory for individual iterator
iterator[i] = malloc(sizeof(person_t)); 
strcpy(iterator[i]->name,names[i]);
iterator[i]->age = ages[i];
strcpy(iterator[i]->job, jobs[i]);
}

for (i = 0; i < capacity; ++i)
{
printf("name = %s ", iterator[i]->name);
printf("Age = %d ", iterator[i]->age);
printf("Job = %sn", iterator[i]->job);
}
return 0;
}

相关内容

  • 没有找到相关文章

最新更新