Why do I have to use malloc when I have a pointer to a struct?

后端 未结 5 421
眼角桃花
眼角桃花 2021-01-23 10:55
 struct element {
     int val;
     int z;
 };
 typedef struct element ELEM;

Look at this example:

 int main()
 {

    ELEM z;
    z =         


        
5条回答
  •  离开以前
    2021-01-23 11:50

    The pointer is only the address of the object in C/C++, not the object itself. In a 32-bit system, its length is always 4 bytes. When you create a pointer, it will refer to a invalid address if you don't initialize it or allocate memory for it. So you must dynamically create the object by calling malloc (in C++, you can use new keyword), then it can refer to the address of the created object.

    ELEM elem; //This will create the object at stack.
    ELEM* pElem; //This just create an invalid poiter which point to unknown address
    pElem = &elem; //This initialize the pointer which point to the address if "elem" above
    pElem = (ELEM*)malloc(sizeof(ELEM)); //This create a new memory which contain the object "ELEM" and pElem will point to the address of the object
    

提交回复
热议问题