在C变量大小的数组 [英] Variable Sized Arrays in C

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

问题描述

在这里的动态内存的讨论:介绍到C指针和动态内存

On the discussion of dynamic memory here: "Intro to C Pointers and Dynamic Memory"

笔者指出:

像这样的存储器块可有效地用作一个更灵活的阵列。这种方法实际上是更常见在真实世界的C程序。它也更predictable和灵活多了一个可变大小的数组

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";

笔者并没有真正摆脱多的光,为什么我要preFER前一种方法后者。或者更具体地说:?它是如何更predictable和灵活的

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数组[变量] 的内存将被分配到堆栈这是不是很对好大的,相对固定的数据结构(比如一个你可能要返回)。你并不需要手动释放内存,如果您使用数组语法,因为它释放时,它超出范围。 ,另一方面释放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变量大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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