我知道2D数组在C中可能会很奇怪,而对于malloc,我会这样做:
/* This is your 2D array. */
double** matrix;
/* The size dimensions of your 2D array. */
int numRows, numCols;
/* Used as indexes as in matrix[x][y]; */
int x, y;
/*
* Get values into numRows and numCols somehow.
*/
/* Allocate pointer memory for the first dimension of a matrix[][]; */
matrix = (double **) malloc(numCols * sizeof(double *));
if(NULL == matrix){free(matrix); printf("Memory allocation failed while allocating for matrix[].\n"); exit(-1);}
/* Allocate integer memory for the second dimension of a matrix[][]; */
for(x = 0; x < numCols; x++)
{
matrix[x] = (double *) malloc(numRows * sizeof(double));
if(NULL == matrix[x]){
free(matrix[x]); printf("Memory allocation failed while allocating for matrix[x][].\n");
exit(-1);
}
}
初始化,有两个fors,数组。
现在,我想将共享内存中的空间分配给一个**数组,但我不知道是否可以这样做:
shmid2 = shmget(IPC_PRIVATE, numCols * sizeof (int*), IPC_CREAT | 0700);
my_array = (double**) shmat(shmid2, NULL, 0);
然后初始化它。这是对的吗。如果没有,我该怎么做?
提前谢谢你
最佳答案
您可以通过一个连续的共享内存段来实现这一点。诀窍在于double
值本身就存在于共享内存中,但是您的double *
行指针可以只是普通的malloc
内存,因为它们只是共享内存的索引:
double *matrix_data;
double **matrix;
int x;
shmid2 = shmget(IPC_PRIVATE, numRows * numCols * sizeof matrix_data[0], IPC_CREAT | 0700);
matrix_data = shmat(shmid2, NULL, 0);
matrix = malloc(numCols * sizeof matrix[0]);
for(x = 0; x < numCols; x++)
{
matrix[x] = matrix_data + x * numRows;
}
(请注意,这是按列主顺序分配索引的,正如您的代码所做的那样,这在C行主顺序中是不寻常的,这更为常见)。
共享共享内存段的各个程序使用
matrix
分配各自的索引malloc
-仅共享实际数组。顺便说一下,您可以对非共享数组使用相同的方法,用一个普通的
malloc()
替换共享内存调用这允许您对整个数组使用一个分配,外加一个用于索引,而您的代码对每列有一个分配。关于c - 如何在C中使用shmget和shmat双数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4222258/