简体   繁体   中英

How to dynamically allocate memory for an array of structs

I am fairly new to C, and am having trouble figuring out how to allocate contiguous memory to an array of structs. In this assignment, we are given a shell of the code, and have to fill in the rest. Thus, I cannot change the variable names or function prototypes. This is what has been given to me:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct student {
    int id;
    int score;
};

struct student *allocate() {
    /* Allocate memory for ten students */
    /* return the pointer */
}

int main() {
    struct student *stud = allocate();

    return 0;
}

I'm just not sure how to go about doing what those comments say in the allocate function.

The simplest way to allocate and initialize the array is this:

struct student *allocate(void) {
    /* Allocate and initialize memory for ten students */
    return calloc(10, sizeof(struct student));
}

Notes:

  • calloc() , unlike malloc() initializes the memory block to all bits zero. Hence the fields id and score of all elements in the array are initialized to 0 .
  • It would be a good idea to pass the number of students as an argument to the function allocate() .
  • It is considered good style to free() allocated memory when you no longer need it. Your instructor did not hint that you should call free(stud); before returning from main() : while not strictly necessary (all memory allocated by the program is reclaimed by the system when the program exits), it is a good habit to take and makes it easier to locate memory leaks in larger programs.

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