how is dynamic memory allocation better than array

2019-08-02 14:57发布

int numbers*;
numbers = malloc ( sizeof(int) * 10 );

I want to know how is this dynamic memory allocation, if I can store just 10 int items to the memory block ? I could just use the array and store elemets dynamically using index. Why is the above approach better ?

I am new to C, and this is my 2nd day and I may sound stupid, so please bear with me.

7条回答
闹够了就滚
2楼-- · 2019-08-02 15:31

The main reason why malloc() is useful is not because the size of the array can be determined at runtime - modern versions of C allow that with normal arrays too. There are two reasons:

  • Objects allocated with malloc() have flexible lifetimes;

That is, you get runtime control over when to create the object, and when to destroy it. The array allocated with malloc() exists from the time of the malloc() call until the corresponding free() call; in contrast, declared arrays either exist until the function they're declared in exits, or until the program finishes.

  • malloc() reports failure, allowing the program to handle it in a graceful way.

On a failure to allocate the requested memory, malloc() can return NULL, which allows your program to detect and handle the condition. There is no such mechanism for declared arrays - on a failure to allocate sufficient space, either the program crashes at runtime, or fails to load altogether.

查看更多
登录 后发表回答