why use malloc with structure?

前端 未结 5 1641
没有蜡笔的小新
没有蜡笔的小新 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:52

    int main() {
        struct node n1;
        n1.data = 99
    

    This reserves space on the stack (in main's frame) equivalent to the size of a struct node. This is known as a local, and it only exists within the context of main.

    struct node *n2 = (struct node *) malloc (sizeof(struct node));
    

    This is an allocation on the heap. This memory exists no matter what function context you are in. This is typically called "dynamic allocation".

    These node structures are the basis for a linked list, which can have nodes added, removed, re-ordered, etc. at will.

    See also:

    • What and where are the stack and heap?

提交回复
热议问题