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

前端 未结 6 1454
傲寒
傲寒 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:51

    malloc() is used whenever:

    1. You need dynamic memory allocation
      If you need to create array of size n, where n is calculated during your program execution, the only way you can do it is using malloc().

    2. You need to allocate memory in heap
      Variables defined in some functions live only till the end of this function. So, if some "callstack-independent" data is needed, it must be either passed/returned as function parameter (which is not always suitable), or stored in heap. The only way to store data in heap is to use malloc(). There are variable-size arrays, but they are allocated on stack.

提交回复
热议问题