静态数据类型是在内存中具有固定大小的数据类型.当我们提前声明数组大小时,在内存中保留了那么多字节或空间,以后不能再增加.所以这样一个数组就是一个静态数据类型.
好.但我们可以使用指针或指针数组动态地将内存分配给数组.我没有清楚地了解整个概念.请帮忙
这些概念是:
// example 1
int array1[256]; // a fixed size, global array of 256 ints, statically allocated
void example2(void)
{
int array2[256]; // an array of fixed size 256, allocated when the function is entered
//...
//... // and automatically released (deallocated) when the function exits
}
void example3(int n)
{
int array3[n]; // an array of fixed size n, allocated when the function is entered
//...
//... // and automatically released (deallocated) when the function exits
}
void example4(int n)
{
int *array4;
array4= malloc(n*sizeof(int)); // a dynamically allocated array
//...
free(array4); // that must be manually deallocated when no longer needed
}
Run Code Online (Sandbox Code Playgroud)
在第一个例子中,数组的大小是在编译时确定的,并且在程序执行期间是固定的.在整个程序执行期间,该数组驻留在全局内存中.
在第二个例子中,数组的大小也在编译时确定,并在程序执行期间保持固定,但是在输入函数时,存储器被分配在堆栈上.因此在递归函数中,可以同时存在多个此数组的出现.
第3个示例使用后面的C标准(VLA)的可变大小的数组.在执行函数期间,数组大小是固定的,但在每次函数调用时都可以更改.如果n很大,那么你可以很容易地耗尽堆栈空间,导致程序崩溃.
第四个示例使用指针从堆中动态分配数组.通过重新分配数组,它的大小也可以在函数调用期间改变.堆通常比堆栈大得多,因此对于大型数组,这种方法是首选.因为数组不驻留在堆栈上,所以可以将其返回给调用者(当不再需要时,必须注意释放它).