Search code examples
cstructdynamic-memory-allocationarray-initialization

Dynamic-memory-allocation of an array within a struct,


I don't understand how to Dynamic allocate memory for an array of structs within another struct. As in, here is my problem... I have a project.c file that contains the main, I have another polynomial.c file that handles all the poly operations like adding terms, multiplying a polynomial by a number ect..

This is header file for polynomials.h

typedef struct term{
    int coeff;
    int expo;
} TERM;

typedef struct polynomial {

int size;
// This needs to be changed to calloc.. not sure how within a struct
TERM terms[20];

} POLYNOMIAL;
...
...

I Also have this within my project.c file which Dynamically allocates memory for the poly array.

POLYNOMIAL *polynomials = (POLYNOMIAL *)malloc(sizeof(POLYNOMIAL) * 8);
// 8 being the max number of polynomials I wan to store

I have two questions here, when and how should I dynamic allocate the memory for the terms array? I was thinking maybe to do a pointer to a pointer who holds the calloc memory for an empty array of terms. This would be done at the program start, but after the polynomial allocation (I think).

Another Question, Now when I go to free the memory should this be done at the end of the program before it exits and the order in which i free should be bottom up, right? In other words, free the terms array then the polynomial array.

At this point any hints or guidance would be helpful. Thanks!


Solution

  • You can simply allocate it with

    TERM *terms = calloc(20, sizeof(TERM));
    

    You can't do it directly within the struct declaration so what you are going to do is something like

    POLYNOMIAL *polynomials = calloc(size, sizeof(POLYNOMIAL));
    
    for (int i = 0; i < size; ++i)
      polynomials[i].terms = calloc(20, sizeof(TERM));
    

    And yes, you will have to free memory bottom up, first you free all the terms, then you free the array of POLYNOMIALS.