why use malloc with structure?

前端 未结 5 1644
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 22:33

Why would I use malloc when same job can be done by without malloc as below..

#include 
#include 

struct node {
    int data;
             


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-14 22:42

    Why would I use malloc when same job cane be done by without malloc as below..

    You use malloc, to allocate memory on heap, and without malloc, you are placing you struct in stack memory.

    I am having hard time to understand how n1 which is not initialized to memory location is able to store data (99) .

    Initialized or not, when you assign data n1.data = 99; , it is stored.

    2) when to use case 1 and when to use case 2

    Case 1 is is used, when you know that you will be using the structure object within a confined scope, and will not be making references to the structure data, beyond its scope.

    Case 2 is used when you will be using your structure at multiple places, and you are willing to manage memory for it manually(and carefully!). The advantage of this method is that, you create and initialize the structure at some part of the program scope, and you create a pointer and pass the pointer around, since passing a 4 byte pointer is far more efficient than , passing the structure itself.

提交回复
热议问题