Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it valid to allocate memory to a structure's pointer without knowing the size of its sub-structures?

Consider the following code:

#include<stdio.h>

struct word {
    char* data;
};

struct sentence {
    struct word* data;
    int word_count;
};

struct paragraph {
    struct sentence* data  ;
    int sentence_count;
};

struct document {
    struct paragraph* data;
    int paragraph_count;
};

void main()
{
    int total_paragraph = 5;   //I'm myself assigning total number of paragraphs for simplicity
    
    struct document doc;
    
    doc.data = malloc(total_paragraph*(sizeof(struct paragraph)));  //Statement which I have a doubt!!!

    ....
    ....
    ....
}

Firstly, logically, Is the statement(malloc one, in which I have a doubt) valid?

If yes, how does the computer assigns 5 units of memory (each unit is of struct paragraph size) without knowing the size of struct paragraph (as we haven’t malloced its content, the pointer data pointing to a struct sentence type)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s impossible to allocate structures without its substructures being defined. After all, you can’t know the size of a structure without knowing the size of its substructures.

However, struct paragraph doesn’t contain any substructures. It contains a structure pointer, an int, and possibly padding. The size of all those things are known.

The code you posted is perfectly fine.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading