动态多维数组
称为动态多维数组、数组的数组是否合适?
int **mp = 0;
// Create an array of pointers
mp = new int*[6];
// Where each element of type pointer, points to dynamic array.
for (int x = 0; x < 6; x++)
mp[x] = new int[7];
看看这个,我想说它们是指向大小为 7 个整数的数组的指针数组。 但是动态数组是否被视为数组或只是指针返回的一块内存?
Is it appropriate to call dynamic multidimesional array, an array of arrays?
int **mp = 0;
// Create an array of pointers
mp = new int*[6];
// Where each element of type pointer, points to dynamic array.
for (int x = 0; x < 6; x++)
mp[x] = new int[7];
Looking at this, I would say they are array of pointers pointing to arrays of size 7 ints.
But are dynamic arrays even considered arrays or just a chuck of memory returned by pointer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果我理解正确的话,你的问题是关于语义的。就标准而言,new [] 确实创建了一个数组,但返回一个指向第一个元素的指针。从标准的5.3.4/5开始:
因此,在您的情况下,我们通俗地称为“数组的数组”实际上是一个指针数组,它与例如
int x[6][6]
不同,后者实际上是一个数组的数组。If I understand correctly, your question is about semantics. As far as the standard is concerned,
new []
does create an array, but returns a pointer to the first element. From 5.3.4/5 of the standard:So in your case, what we colloquially call "an array of arrays" is really an array of pointers, which is distinct from e.g.
int x[6][6]
, which is truly an array of arrays.是的,它们是指针数组。数组的数组有所不同:
指针数组通常在 C 中使用,因为在该语言中没有其他方法可以在运行时创建多索引数据结构。
Yes, they are arrays of pointers. Arrays of arrays are different:
Arrays of pointers are commonly used in C since there is no other way to create multi-indexed data structures at run time in that language.
C++(和 C)对不规则数组和连续多维数组的处理方式截然不同。访问元素看起来是相同的,但在底层却有很大不同。
第一次访问只需要通过一个指针一次,而第二次访问则需要通过两个指针。
C++ (and C) treat ragged arrays and contiguous multidimensional arrays quite differently. Access an element appears to be the same, but is quite different underneath the hood.
The first access requires going through a pointer only once while the second requires going through two pointers.
我将数组视为指针,因为实际上保存数组的变量只是指向数组第一个元素的指针。此外,您可以在任何指针中使用operator[],即使它不指向数组。
按照这个思路:
mp是一个指向“整数指针块”的指针,mp[x]是一个指向“整数块”的指针。
现在,这些“内存块”就是我所认为的数组,所以你有:
mp是一个指向整数指针数组的指针,mp[x] 是一个指向整数数组的指针。
在您的示例中,您总共有 7 个数组(内存块),每个 new 语句对应一个数组。使用完该结构后,请不要忘记删除[]其中的每一个。
I think of arrays as pointers, because in practice a variable that holds an array is just a pointer to the first element of the array. Furthermore, you can use operator[] in any pointer, even if it's not pointing to an array.
With that line of thought:
mp is a pointer to a "chunk of integer pointers", and mp[x] is a pointer to a "chunk of integers".
Now, these "chunks of memory" is what I would think of as the array, so you've got:
mp is a pointer to an array of integer pointers, and mp[x] is a pointer to an array of integers.
In your example you've got a total of 7 arrays (chunks of memory), one for every new statement. Don't forget to delete[] every one of them after you're done using the structure.