gpt4 book ai didi

c - 数组是静态数据结构。那么内存如何动态分配给它们呢?

转载 作者:太空宇宙 更新时间:2023-11-04 05:22:52 25 4
gpt4 key购买 nike

静态数据类型是一种在内存中具有固定大小的数据类型。由于我们提前声明了数组大小,因此在内存中保留了那么多字节或空间,以后无法增加。所以这样一来,数组就是静态数据类型。

好的。但是我们可以使用指针或指针数组为数组动态分配内存。我不清楚整个概念。请帮忙

最佳答案

概念是:

// 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
}

在第一个示例中,数组的大小在编译时确定,并在程序执行期间固定。该数组在程序的整个执行过程中都驻留在全局内存中。

在第二个例子中,数组的大小也是在编译时确定的,并在程序执行期间保持不变,但在进入函数时,内存是在堆栈上分配的。所以在一个递归函数中,这个数组可以同时存在不止一次。

第三个示例使用后来的 C 标准 (VLA) 的可变大小数组。数组大小在函数执行期间是固定的,但可以在每次函数调用时更改。如果 n 很大,那么您很容易用完堆栈空间,导致程序崩溃。

第 4 个示例使用指针从堆中动态分配数组。通过重新分配数组,它的大小也可以在函数调用期间发生变化。堆通常比堆栈大得多,因此对于大型数组,首选此方法。因为数组不驻留在堆栈上,所以您可以将它返回给调用者(调用者必须在不再需要时注意释放它)。

关于c - 数组是静态数据结构。那么内存如何动态分配给它们呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52665411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com