gpt4 book ai didi

C 3d 数组动态内存分配,问题,需要帮助

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:43 26 4
gpt4 key购买 nike

我在网上寻找一种为 3d 矩阵动态分配空间的方法,比如 int 类型。我发现很多关于二维矩阵的网站,这个 http://www.taranets.com/cgi/ts/1.37/ts.ws.pl?w=329;b=286并且有这个例子如下所示。我理解以上所有示例,但我不能理解关于 3d 的这个。创建者是在向后分配空间还是以其他方式分配空间?他从为整个矩阵分配空间开始,然后进行到 Z 轴?这就是我无法理解的。

此外,如果您知道任何与此相关的好网站,请在此处发布,我们将不胜感激。

    /* Program 9.4 from PTRTUT10.HTM   6/13/97 */
// http://www.taranets.com/cgi/ts/1.37/ts.ws.pl?w=329;b=286

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

int X_DIM=16;
int Y_DIM=5;
int Z_DIM=3;

int main(void)
{
char *space;
char ***Arr3D;
int y, z;
ptrdiff_t diff;

/* first we set aside space for the array itself */

space = malloc(X_DIM * Y_DIM * Z_DIM * sizeof(char));

/* next we allocate space of an array of pointers, each
to eventually point to the first element of a
2 dimensional array of pointers to pointers */

Arr3D = malloc(Z_DIM * sizeof(char **));

/* and for each of these we assign a pointer to a newly
allocated array of pointers to a row */

for (z = 0; z < Z_DIM; z++)
{
Arr3D[z] = malloc(Y_DIM * sizeof(char *));

/* and for each space in this array we put a pointer to
the first element of each row in the array space
originally allocated */

for (y = 0; y < Y_DIM; y++)
{
Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM);
}
}

/* And, now we check each address in our 3D array to see if
the indexing of the Arr3d pointer leads through in a
continuous manner */

for (z = 0; z < Z_DIM; z++)
{
printf("Location of array %d is %p\n", z, *Arr3D[z]);
for ( y = 0; y < Y_DIM; y++)
{
printf(" Array %d and Row %d starts at %p\n", z, y, Arr3D[z][y]);
diff = Arr3D[z][y] - space;
printf(" diff = %d ",diff);
printf(" z = %d y = %d", z, y);
}
putchar('\n');
}
putchar('\n');
system("PAUSE");
return 0;
}

最佳答案

空间确实是为整个矩阵分配的内存。

然而,他继续用

创建指向空间中区域的指针
Arr3D = malloc(Z_DIM * sizeof(char **));

Arr3D 的目的只是一种通过索引(指定 Z、Y、X 索引)访问空间的方法。 Space 只有一个索引,所以如果你想通过 space 访问矩阵元素 [a][b][c],你需要将它转换为单个 space[d] 其中 d 类似于 a*Y_DIM*Z_DIM + b*Z_DIM+c。因此,使用 Arr3D,您可以通过 Arr3D[a][b][c] 访问 [a][b][c]

Arr3D本身就是一个char**的数组,是指向char类型指针的指针。Arr3D[z] 是一个指向 char 指针数组的指针。然后将每个 Arr3D[z][y] 设置为指向原始 3x3 矩阵中的特定行

Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM);

然后使用 Arr[1][2],您将访问矩阵的 z=1, y=2 行。

关于C 3d 数组动态内存分配,问题,需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2193278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com