问题描述
int length = 5;
int hi[length];
vs
int length = 5;
int *hi = new int[length];
有人告诉我,当您尝试使用大小不是恒定的数组静态分配数组时,编译器会抱怨用C语言编写.因此,如果您需要未知大小的数组,则需要动态分配内存.但是,既然有允许第一个示例的编译器,它们究竟在做什么?它们仍在数据段中,还是不在堆中?如果它们在堆上,那么示例之间有什么区别,为什么我仍然必须在第二个示例而不是第一个示例上调用delete []?
I was taught compilers complain in C whenever you try to statically allocate arrays w/ size that's not constant. So if you ever needed array of unknown size, you needed to dynamically allocate memory. However, now that there are compilers that allow the first example, what exactly are they doing? Are they still going in the data-segment, or are they not going on the heap? If they're going on the heap, then what is the difference between the examples, and why would I still have to call delete[] on the 2nd example, but not the 1st example?
推荐答案
第一个是声明一个 static 变量(通常在堆栈上*),该变量将在定义它的代码块的末尾 die 消失.
The first one is declaring a static variable (usually on the stack*) that will die at the end of the code block in which it is defined.
第二个是动态分配一个变量(通常在堆上*),这意味着您可以决定用delete[]
在哪里分配它(是的,您应该记住要这样做).
The second one is dynamically allocating a variable (usually on the heap*) which means that you are the one that can decide where to deallocate it with delete[]
(and yes you should remember to do it).
在数组上下文中,两者之间的主要区别在于,可以通过取消分配它所指向的内存(例如,先前的数组)并使其指向仍然动态分配的新数组来轻松地调整第二个数组的大小./p>
The main difference between the two, in the array context, is that the second one can be easily resized by deallocating the memory it points (the previous array for example) and make it point to a new array still dynamically allocated.
int* arr = new int[5];
[...]
delete[] arr;
arr = new int[10];
静态数组int hi[length]
通常声明一个const int*
,而不应该对其进行修改.也就是说,C ++提供了一整套可以/应该使用而不是数组的容器.
Static arrays int hi[length]
usually declare a const int*
which shouldn't be modified instead. It is to say that C++ provides a complete set of containers that can / should be used instead of arrays.
[*] 注意:C ++标准未指定分配动态或静态内存的位置.
这篇关于C ++此数组的静态分配和动态分配有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!