What is the difference between static and dynamic arrays in C? [duplicate]

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

Possible Duplicate:
Is array name a pointer in C?
C++ Static array vs. Dynamic array?

I'm learning C and I'm confused at what the difference is between the following two arrays:

int a[10]; 

and

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

Just on the most basic level, what is the difference between these two?

回答1:

int a[10]; 

is allocated on stack and is de-allocated as soon as the scope ends.

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

is allocated on heap and is alive throughout the lifetime of the program unless it's explicitly freed.



回答2:

The static array will be destroyed as soon as you leave the current stack frame (basically, when the function you're in returns). The dynamic array sticks around forever until you free() it.



回答3:

The first lives on the stack (= lives as long as the scope of the variable), the second lives on the heap (= lives until freed). The first has a fixed size, whereas the second can be re-sized.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!