3

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 3
    because they are pointers. Compiler knows how much memory to allocate for pointers. – miradham Nov 14 '17 at 07:17
  • They're pointers - a varaible that holds the address of another. The delivery address field on an online sales form is the same size no matter whether the delivery is to an economy apartment or a billionaire mansion. – Martin James Nov 14 '17 at 10:41

3 Answers3

2

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

miradham
  • 2,285
  • 16
  • 26
  • sir, you mean the pointer of all type is same size under one machine?so complier allocate the same size to all type pointer? –  Nov 14 '17 at 07:23
  • 1
    @linsir I think you're mixing up the _size of the pointer_ (usually 4 bytes on a 32 bit system and 8 bytes on a 64 bbit system) and the _size of the object the pointer points to_. – Jabberwocky Nov 14 '17 at 07:26
  • 1
    @linsir pointer size depends on different factors. But in general yes. You can check it by printing out `sizeof(int*)` and `sizeof(struct Node*)` – miradham Nov 14 '17 at 07:29
  • @linsir, generally, yes. The standard states that pointers to data types are the same size on a system. But pointer to a function does not need to be (though it's mostly same, except some architectures). – AlbusMPiroglu Nov 14 '17 at 09:05
1

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

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.

sorush-r
  • 10,490
  • 17
  • 89
  • 173