Structure memory allocation

风格不统一 提交于 2019-12-12 13:13:12

问题


struct node{
  int data;
  struct node * next;
};

How does the compiler allocate memory for "next" member in when we have not yet allocated memory for the structure "struct node"


回答1:


next member is a pointer - a variable that will contain an address of node, not node itself. All data type pointers are usually of the same size so it's enough for the compiler to know that it's a pointer to be able to compute its size.




回答2:


The member next is a pointer. Pointers are all the same size, so the compiler does not need to know how big the thing that next may point to is.




回答3:


Next is only a pointer so it is a fixed size value in every machine, it'll just add int+pointer sizes + padding and allocate node struct




回答4:


it happens dynamically when you use malloc. Otherwise nothing is allocated. All the compiler does is just allocate the 4 bytes for the pointer which will hold the address of the "to-be" allocated memory. If you try to access the pointer without allocating any memory, the code will crash (u'll end up accessing some invalid memory in the program)



来源:https://stackoverflow.com/questions/1299218/structure-memory-allocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!