简体   繁体   中英

How can I initialize and dynamically allocate an int pointer member in an array of structs?

How can I initialize and dynamically allocate an int pointer that is in an array of structs?

My program allows me to print enroll[0].grades[x] , but when I try to access any other index value of enroll other than 0 (such as enroll[1].grades[x] or enroll[2].grades[x] ), my program segmentation faults.

Here's my code...

How can I make enroll[2].grades[x] , for example, initialize and equal zero?

In my struct:

struct Enroll
{
        int *grades;
};

In main:

struct Enroll *enroll = (struct Enroll *) calloc(count.enroll, 10 * sizeof(struct Enroll));

enroll->grades = (int *) calloc(count.grades, 10 * sizeof(int));

In functions:

enroll[x].grades[y];

In main you should have

struct Enroll *enroll =  calloc(count.enroll, sizeof(struct Enroll));

for(int i = 0; i < count.enroll ;i++)
{
    enroll[i].grades =  calloc(count.grades,  sizeof(int));
}

In your code you have not allocated memory for each integer pointer.

Allocate memory for number of struct Enrollements

struct Enroll *p = calloc(count.enroll, sizeof(struct Enroll));

Now you have the number of structures to be filled in and what you need is memory for the int pointer to hold values and the number of int pointers is count.enroll

for(i=0;i<count.enroll;i++)
{
   p[i].grades = calloc(count.grades,sizeof(int)); 
   // Fill in the values
}

PS: Alternatively you can go for malloc() followed by memset()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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