Home > Net >  Is it valid to allocate memory to a structure's pointer without knowing the size of its sub-str
Is it valid to allocate memory to a structure's pointer without knowing the size of its sub-str

Time:12-22

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)?

CodePudding user response:

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.

CodePudding user response:

without knowing the size of struct paragraph (as we haven't malloced its content, the pointer data pointing to a struct sentence type)? c pointers struct

Why do we need to malloc a structure to know it's size? What is the size of this structure?

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

It has a pointer and an integer. A pointer has a fixed size(usually 64-bit on 64-bit machines and 32-bit on 32-bit machines) and and integer has a fixed size(usually 32 bit). so, the size of the struct in bytes is sizeof(any_pointer) sizeof(int) padding. All of those three are known to the compiler.

  • Related