我在某处看到了以下代码,我有点困惑。
int**** m_ppppCoder;
m_ppppCoder = new int ***[10];
那是动态分配的 3 维 int 数组吗?有人可以准确解释它是如何工作的吗?
阅读评论后添加: 上面的声明本身并不是一个完整的 3d int 数组,而是包含创建数组第一步的声明结构。据此,使用下面的代码,您可以动态创建一个 3d 数组。对吗?
m_ppppCoder[0] = new int **[10];
m_ppppCoder[0][0] = new int *[10];
m_ppppCoder[0][0][0] = new int[10];
在这种情况下,实际数据如何在内存中按顺序排列(分配)?
最佳答案
Is that a 3 dimensional int array that allocated dynamically ?
没有。
int**** m_ppppCoder
m_ppppCoder
是一个指针,指向一个指向整数的指针。
m_ppppCoder = new int * **[10];
m_ppppCoder
指向一个动态分配的数组的第一个元素,该数组包含 10 个指向整数指针的指针。
Can someone explain exactly, how it works ?
好吧,它是一个指向数组元素的指针,所以它本身并没有做太多的工作。使用示例:
int i = 42; // an integer i
int *ii = &i; // ii points to i
int **iii = ⅈ // iii points to ii
m_ppppCoder[0] = &iii; // the first element points to iii
int j = ****m_ppppCoder[0]; // the value of j is now 42
delete[] m_ppppCoder; // never forget to delete dynamic memory
int****
可能没有很好的实际用途。
m_ppppCoder = new int ***[10]; m_ppppCoder[0] = new int **[10]; m_ppppCoder[0][0] = new int *[10]; m_ppppCoder[0][0][0] = new int[10];
In this case, the actual data how are arranged (allocated) inside the memory ie sequentially ?
像这样:
pointer to int*** p
|
an array of 10 int*** |->[0][1][2][3]...
|
an array of 10 int** |->[0][1][2][3]...
|
an array of 10 int* |-> [0][1][2][3]...
|
an array of 10 int |-> [0][1][2][3]...
这很简单。你已经分配了 4 个数组。由于它们是单独分配的,因此这 4 个数组中的每一个都彼此分开,位于自由存储区的某个位置。
数组的元素本身在内存中是连续的。因此,每个指针(或最后一个指针的整数)在内存中相对于同一数组的其他元素是连续的。
请注意,m_ppppCoder[x]
、m_ppppCoder[0][x]
和 m_ppppCoder[0][0][x]
是[1, 10] 中所有 x 的未初始化指针。
关于c++ - "new int * **[10]"是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51671980/