我知道二維數組可以在C怪異,並且使用malloc,我會做這樣的事情:如何在C中shmget和shmat雙數組?
/* 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);
}
}
和初始化,2個FORS,數組。 現在,我想分配共享內存空間爲**陣列,但我不知道如果我能做到這一點:
shmid2 = shmget(IPC_PRIVATE, numCols * sizeof (int*), IPC_CREAT | 0700);
my_array = (double**) shmat(shmid2, NULL, 0);
,然後對其進行初始化。它是否正確。如果不是,我該如何正確地做到這一點?
預先感謝您
另外,'if(NULL == matrix){free(matrix);'不正確。 – 2010-11-19 05:22:20
'free(NULL)'被標準化爲無操作,但是你是對的,它並不真正「正確」。 – dreamlax 2010-11-19 05:32:07