gpt4 book ai didi

c - 如何索引到 3-D 动态数组?

转载 作者:行者123 更新时间:2023-12-04 09:46:59 24 4
gpt4 key购买 nike

我以这种方式创建了一个 3 维动态数组:

double *A = (double *)malloc(M * N * N * sizeof(int));

这相当于静态矩阵:

double A[M][N][N];

我想引用实现静态行为的每个索引:

for (j = 0; j < N; j++) {

for(i = 0; i < N; i++) {

for(k = 0; k < M; k++) {

if (i!=j)
A[k][j][i] = (y[j]*gain[k][i])/gain[k][j];
else
A[k][j][i] = 0;

printf("%f ", A[k][j][i]);
}

}
}

所以我尝试了这个:

    for (j = 0; j < N; j++) {       //matrix A

for(i = 0; i < N; i++) {

for(k = 0; k < M; k++) {

if (i!=j)
*(A + k*N + j + i) = (*(y+j) * *((gain+k*N)+i)) / *((gain+k*N)+j);
else
*(A + k*N + j + i) = 0;

printf("%f ", *(A + k*N + j + i));
}

}
}

这是正确的语法吗?

最佳答案

用动态版本替换静态 double A[M][N][N]

double *A = (double *)malloc(M * N * N * sizeof(double)) 没有 sizeof(int)

在动态分配情况下,静态A[k][j][i] 的使用将被替换为

A[k * (N * N) + j * N + i]

用一些示例代码扩展答案:

#include <assert.h>
#include <stdlib.h>

int main(void) {
int a5x3x2[5][3][2] = {{{4, 6}, {4, 6}, {4, 6}},
{{4, 6}, {4, 6}, {4, 6}},
{{4, 6}, {4, 6}, {4, 6}},
{{4, 6}, {4, 6}, {4, 6}},
{{4, 6}, {4, 6}, {4, 6}}};
int a2x3x5[2][3][5] = {{{7, 8, 9, 10, 11}, {7, 8, 9, 10, 11}, {7, 8, 9, 10, 11}},
{{7, 8, 9, 10, 11}, {7, 8, 9, 10, 11}, {7, 8, 9, 10, 11}}};

int const x = 1;
int const y = 1;
int const z = 1;

a5x3x2[x][y][z] = 42;
int *p = &a5x3x2[0][0][0];
assert(p[x * (3 * 2) + y * (2) + z] == 42);

a2x3x5[x][y][z] = 24;
p = &a2x3x5[0][0][0];
assert(p[x * (3 * 5) + y * (5) + z] == 24);

return EXIT_SUCCESS;
}

这是一个显示通用逻辑的完整 3D 示例:

#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
enum { Xsize = 3, Ysize = 5, Zsize = 7 };
double static3D[Zsize][Ysize][Xsize];
double* dynamic3D = (double*)malloc(Zsize * Ysize * Xsize * sizeof(double));
for (int z = 0; z < Zsize; ++z)
for (int y = 0; y < Ysize; ++y)
for (int x = 0; x < Xsize; ++x)
static3D[z][y][x] = dynamic3D[z * (Ysize * Xsize) + y * Xsize + x] =
(x + 1) * (y + 1) * (z + 1);
assert(memcmp(static3D, dynamic3D, sizeof(static3D)) == 0);
free(dynamic3D);
return EXIT_SUCCESS;
}

关于c - 如何索引到 3-D 动态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57051728/

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