gpt4 book ai didi

c - 可变大小数组与 C 中的 calloc

转载 作者:太空狗 更新时间:2023-10-29 17:05:12 26 4
gpt4 key购买 nike

关于动态内存的讨论在这里:"Intro to C Pointers and Dynamic Memory"

作者说:

A memory block like this can effectively be used as a more flexible array. This approach is actually much more common in real-world C programs. It's also more predictable and flexible than a "variable size array"

他说的内存块类型是这样的:

const int size = 5;
int * array = calloc(size, sizeof(int));

然后使用另一个指针遍历数组:

int * index = array;
for (i = 0; i < size; i++) {
*index = 1; // or whatever value
index++;
}

我的问题是这种方法比像这样的标准可变大小数组好在哪里?

int array[variable];

或动态:

char name[] = "Nick";

作者并没有真正阐明为什么我应该更喜欢前一种方法而不是后者。或者更具体地说:它如何更“可预测和灵活”?

最佳答案

如果您声明 int array[variable],内存将分配到堆栈上,这对于大型、相对永久的数据结构(例如您可能想要返回的数据结构)来说不是很好。如果您使用数组语法,则不需要手动释放内存,因为它在超出范围时会被释放。另一方面,calloc 将在运行时在堆上动态分配内存。您必须在完成后立即自行释放它。

关于c - 可变大小数组与 C 中的 calloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/448844/

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