When declaring variable is not completed, why compiler know its size?

Viewed 75

After pointer pa declaring, right now,to use it in the function malloc(),

why compiler can know its size? And compiler how to parse under code:

int *pa = malloc(10 * sizeof *pa); // allocate an array of 10 int

and

struct Node {
    int value;
    struct Node *prev;
    struct Node *next;  
}

prev and next is struct Node *, but now struct Node is undefined.

Why compiler is able to allocate enough size for *prev, *next?

3 Answers

Because they are pointers. Compiler knows how much memory to allocate for pointers.

In case of the structure declaration shown here, the member variables you are interested in are pointer-to-some-type.

For any given environment, a pointer (to type) holds a defined size. While allocating memory for a variable of the type, compiler need not know the actual size for the type, it just needs to know the size required for a pointer to that type and it knows that.

Compiler does not allocate enough space for a Node structure, inside a Node structure. Though it does know how much a pointer needs, and allocates enough space for two pointers and in integer.

Related