why use malloc with structure?

前端 未结 5 2189
予麋鹿
予麋鹿 2021-02-14 22:08

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:56

    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?

提交回复
热议问题