gpt4 book ai didi

c - 如何在 C 中初始化 3D 连续数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:22 24 4
gpt4 key购买 nike

我知道如何通过以下方式创建潜在的非连续数组:

int main () {
int ***array = (int***)malloc(3*sizeof(int**));
int i, j;

for (i = 0; i < 3; i++) {
// Assign to array[i], not *array[i] (that would dereference an uninitialized pointer)
array[i] = (int**)malloc(3*sizeof(int*));
for (j = 0; j < 3; j++) {
array[i][j] = (int*)malloc(3*sizeof(int));
}
}

array[1][2][1] = 10;

return 0;
}

使用上面的代码,array[0][j] block 可以不连续。为了连续,我觉得我们需要这样malloc

int* array = (int*)malloc(3*3*3*sizeof(int));
int** y = (int**)malloc(3*3*sizeof(int**));
int*** x = (int***)malloc(3*sizeof(int***));

for(i = 0; i < 3; i++)
{
vals = vals + i*m*n;
x[i] = &vals;
for(j = 0; j < 3; j++)
{
x[i][j] = vals + j * n;
}
}

但是,我在地址分配方面遇到了麻烦。我不是c程序员,谁能纠正我的错误?提前致谢...

最佳答案

int*** x = (int***)malloc(3*sizeof(int***));

应该是

int*** x = (int***)malloc(3*sizeof(int**));

现在初始化可以是:

  for(i = 0; i < 3; i++)
{
x[i] = y + 3*i;
for(j = 0; j < 3; j++)
{
x[i][j] = array + i*3*3 + j*3;
}
}

因此x[0] 指向y 的第一个元素,x[1] 指向第四个,等等。而 x[0][0]=y[0]array 的第一个,x[0][1] =y[1]array的第四位等

关于c - 如何在 C 中初始化 3D 连续数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32873750/

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