why use malloc with structure?

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

    Normally you use malloc only, if you don't know the size of memory you will need before the application is running.

    Your code is correct, but you can't allocate memory dynamically. What if you want to save a measured value in the node.date and you don't know, how many measures you will capture? Then you have to malloc some new memory on each measure you take.

    If you define all the nodes before run-time (directly in the code), you can't save more measures than you've defined before.

    Search for linked lists in c and you will find some good examples.

提交回复
热议问题