I have a code with a memory allocation for 3D array called "matrix" which I generally index for the x,y,z direction as matrix[i][j][k]
where i
,j
and k
are the index in x, y and z direction respectively. The allocation procedure that has been followed in the code is as follows ( lr is just a typedef for double )
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;
}
Now, I want to port this code in a way that this matrix can be accessed in a same way using Shared Memory IPC with another code. So if i declare the memory as
ShmID = shmget(ShmKEY, m*n*o*sizeof(lr), IPC_CREAT | 0666);
then how should I attach this block of memory to a tripple pointer such that the memory access remains same ?
example for attaching this as a single pointer I can write
matrix = (lr *) shmat(ShmID, NULL, 0);
Also I am bit struggling with the for
loops in the original code and what they are actually doing ?
Edit: ShmKEY is just an identifier known apriori.