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