【发布时间】:2018-04-06 08:52:22
【问题描述】:
我有一个为 3D 数组分配内存的代码,称为“矩阵”,我通常将 x、y、z 方向索引为matrix[i][j][k],其中i、j 和k 是索引x、y 和 z 方向。代码中已经遵循的分配过程如下(lr只是double的typedef)
lr ***lr_3D_matrix(int m, int n, int o)/** \brief create a 3D matrix with size [m, n,o] of type lr*/
{
lr ***matrix;
int i, j;
matrix = malloc(m * sizeof(lr **)); //allocate first dimension
matrix[0] = malloc(m * n * sizeof(lr *)); //allocate continous memory block for all elements
matrix[0][0] = malloc(m * n * o * sizeof(lr))
for(j = 1; j < n; j++) //fill first row
{
matrix[0][j] = matrix[0][j - 1] + o; //pointer to matrix[0][j][0], thus first element of matrix[0][j][o]
}
for(i = 1; i < m; ++i)
{
matrix[i] = matrix[i - 1] + n; //pointer to position of to matrix[i][0]
matrix[i][0] = matrix[i - 1][n - 1] + o; //pointer to matrix[i][j][0];
for(j = 1; j < n; ++j)
{
matrix[i][j] = matrix[i][j - 1] + o;
}
}
return matrix;
}
现在,我想移植此代码,以便可以使用共享内存 IPC 和其他代码以相同的方式访问此矩阵。因此,如果我将内存声明为
ShmID = shmget(ShmKEY, m*n*o*sizeof(lr), IPC_CREAT | 0666);
那么我应该如何将这块内存附加到三元组指针,以使内存访问保持不变?
将其作为我可以编写的单个指针附加的示例
matrix = (lr *) shmat(ShmID, NULL, 0);
另外,我对原始代码中的 for 循环以及它们实际在做什么感到有些苦恼?
编辑:ShmKEY 只是一个已知的标识符。
【问题讨论】:
-
@Someprogrammerdude 我的错,这是一个错字。实际上它应该是 mno*sizeof(lr)。但问题仍然存在。 (这是一个错字,现已更正)
-
您需要使用实际的 3D 数组。见Correctly allocating multi-dimensional arrays。
-
我会说
matrix[0][0] = shmat(ShmID, NULL, 0);和其他一切都保持不变。 -
@user3386109 我确实明白了你的意思,但是必须为矩阵(如***)、矩阵[0](如**)赋值,然后它们必须交织在一起可以再次以
matrix[i][j][k]的身份访问矩阵(这是参考需要访问矩阵的其他代码。对于此代码,我确实明白您的观点,即仅更改行将保持其他内容不变。) -
matrix和matrix[0]的分配不需要在共享内存中。只有double值本身需要在共享内存中。 OTOH Lundin 是正确的,您可以声明一个指针lr (*matrix)[n][o] = shmat(ShmID, NULL, 0);并改用它,假设编译器支持 VLA。
标签: c arrays memory multidimensional-array ipc