What are some useful examples of malloc() in C?

前端 未结 6 1457
傲寒
傲寒 2020-12-15 08:16

I\'m just reading about malloc() in C.

The Wikipedia article provides an example, however it justs allocate enough memory for an array of 10 ints in com

6条回答
  •  一生所求
    2020-12-15 08:45

    What if you don't know the size of the array when you write your program ? As an example, we could imagine you want to load an image. At first you don't know its size, so you will have to read the size from the file, allocate a buffer with this size and then read the file in that buffer. Obviously you could not have use a static size array.

    EDIT:

    Another point is: When you use dynamic allocation, memory is allocated on the heap while arrays are allocated on the stack. This is quite important when you are programming on embedded device as stack can have a limited size compared to heap.

提交回复
热议问题