简体   繁体   English

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

[英]Accessing members of dynamically allocated array of pointers to structs

I need to have a global dynamic array of pointers, in which I will store my structs, beacuse later I will need to iterate through this array to list all the stored information, I also need to be able to read the name , age and job variables from the console, and store them in a person_t in the iterator array.我需要一个全局动态指针数组,我将在其中存储我的结构,因为稍后我需要遍历此数组以列出所有存储的信息,我还需要能够读取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;
}

I get no errors/warnings compiling this code (gcc -ansi -pedantic -Wall -Wextra), but when I try to run it, I get a Segmentation fault immediately.我在编译此代码 (gcc -ansi -pedantic -Wall -Wextra) 时没有收到任何错误/警告,但是当我尝试运行它时,我立即收到Segmentation fault

When you do this:当你这样做时:

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

You're deferencing iterator , however as a file-scope pointer variable it's initialized to NULL. Attempting to dereference a NULL pointer invokes undefined behavior .您正在取消引用iterator ,但是作为文件范围指针变量,它被初始化为 NULL。尝试取消引用 NULL 指针会调用未定义的行为

I suspect what you really want is an array of structs, not an array of pointers to structs.我怀疑您真正想要的是一个结构数组,而不是一个指向结构的指针数组。 That being the case, define iterator as:既然如此,定义iterator为:

person_t *iterator;

Then you allocate memory for it like this:然后像这样为它分配 memory:

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

Then assign to array elements like this:然后像这样分配给数组元素:

iterator[i] = p;

Your stated purpose is to create a "global dynamic array of pointers, in which I will store my structs" .您声明的目的是创建一个“全局动态指针数组,我将在其中存储我的结构” The following modification of your code (see comments) will do this:对您的代码进行以下修改(请参阅评论)将执行此操作:

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: %s\n",  i, iterator[i]->name,iterator[i]->age,iterator[i]->job);
        }

    return 0;
}

you are not allocating memory correctly你没有正确分配 memory

First you need to allocate memory for a pointer which can store capacity number of address ie done through iterator = malloc(capacity * sizeof(person_t*));首先,您需要为一个指针分配 memory,该指针可以存储地址的capacity数,即通过iterator = malloc(capacity * sizeof(person_t*)); and then you need to allocate memory for holding each structure element ie iterator[i] = malloc(sizeof(person_t));然后你需要分配 memory 来保存每个结构元素,即iterator[i] = malloc(sizeof(person_t));

all the malloc 'ed memory should be free 'd once we are done with it.一旦我们完成了它,所有malloc和 memory 应该是free的。

Also, have not done the error check for malloc 's, that is left as an exercise for you.此外,还没有对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 = %s\n", iterator[i]->job);
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM