如何在C中shmget和shmat双数组?

我知道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); } } 

和2个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中是不常见的 - 行主要顺序更常见)。

共享共享内存段的独立程序使用malloc分配它们自己的索引matrix - 只共享实际数组。

顺便说一下,您可以对非共享数组使用相同的方法,用普通的malloc()替换共享内存调用。 这允许您对整个数组使用单个分配,加上一个用于索引,而您的代码每列有一个分配。

我做到了! 我将给出一个结构,然后是一个双数组,但是你得到了重点。

所以,基本上我想在一段共享内存中分配一个**像素,pixel_data(结构image_struct的成员,这里实例化为图像)。

  shmid2 = shmget(IPC_PRIVATE, image->width * sizeof (pixel*), IPC_CREAT | 0700); image->pixel_data = (pixel**) shmat(shmid2, NULL, 0); /* Allocate integer memory for the second dimension of **pixel_data; */ for (i = 0; i < image->width; i++) { shmPixelId = shmget(IPC_PRIVATE, image->height * sizeof (pixel), IPC_CREAT | 0700); image->pixel_data[i] = (pixel *) shmat(shmPixelId, NULL, 0); if ( image->pixel_data[i]== NULL) { shmdt(image->pixel_data[i]); printf("Sh_Memory allocation failed while allocating for pixel_data[i][].\n"); exit(-1); } } 

我的结构:

 typedef struct pixel_t { byte red; byte green; byte blue; }pixel; typedef struct { int width; int height; pixel **pixel_data; } image_struct; 

我遵循与malloc维度数组相同的代码,但我使用了共享内存。

我不会这样做,即使使用malloc,因为一旦数组变大,内存碎片化。 使用shmget你也会遇到fd的问题(每个shmget使用一个fd)。

我建议这样做(未编译,因为没有C编译器关闭)

 double* matrix = malloc( sizeof(double)*numrows*numcols); double value = matrix[actrow*numrows+actcol]; free ( matrix); 

您必须记住整个应用程序中的数字,但这样从内存方面来说它更加干净。 此外,现在它是一个很大的块,你可以用shmget / shmat做同样的事情。