可变大小的数组与 C 中的 calloc [英] Variable Sized Arrays vs calloc in C

查看:49
本文介绍了可变大小的数组与 C 中的 calloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于动态内存的讨论:C 指针和动态内存简介"

作者声明:

像这样的内存块可以有效地用作更灵活的数组.这种方法实际上在现实世界的 C 程序中更为常见.它也比可变大小的数组"更具可预测性和灵活性

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"

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

The type of memory block he is talking about is as such:

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

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

and then using another pointer to iterate over the array:

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

我的问题是这种方法如何比这样的标准可变大小数组更好?:

My question is how is this method better than a standard variable sized array like this?:

int array[variable];

或动态:

char name[] = "Nick";

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

The author doesn't really shed much light as to why I should prefer the former method to the latter. Or more specifically: How is it more "predictable and flexible"?

推荐答案

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

If you declare int array[variable] the memory will be allocated on the stack which is not very good for large, relatively permanent data structures (such as one you might want to return). You don't need to free memory manually if you use the array syntax since it's freed when it goes out of scope. calloc on the other hand will allocate memory dynamically at run time on the heap. You'll have to free it yourself as soon as you're finished with it.

这篇关于可变大小的数组与 C 中的 calloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆