怎样的shmget和SHMAT在C双数组

怎样的shmget和SHMAT在C双数组

本文介绍了怎样的shmget和SHMAT在C双数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道二维数组可以用C怪异,并使用malloc,我会做这样的事情:

I know 2D array can be weird in C, and with malloc, i would do something like this:

/* 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维权,阵列。
现在,我想分配共享内存空间为**数组,但我不知道如果我能做到这一点:

and the initialize, with 2 fors, the array.Now, I want to allocate space in shared memory to a **array, but I don't know if I can do this:

shmid2 = shmget(IPC_PRIVATE, numCols * sizeof (int*), IPC_CREAT | 0700);
my_array = (double**) shmat(shmid2, NULL, 0);

,然后初始化。它是否正确。如果没有,我怎么能这样做的正确方法?

and then initialize it. Is this correct. If not, how can I do this the right way?

感谢您提前

推荐答案

您可以用一个连续的共享内存段做到这一点。诀窍是,双击值本身住在共享内存,但你的双* 行指针一样可以定期的malloc 记忆,因为他们只是一个索引共享内存:

You can do this with a single contiguous shared memory segment. The trick is that the double values themselves live in the shared memory, but your double * row pointers can be just regular malloc memory, since they're just an index into the shared memory:

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;
}

(注意,这在分配列主顺序指数,作为你的code呢,这是​​不寻常用C - 行主顺序为多见)。

(Note that this allocates the index in column-major order, as your code does, which is unusual in C - row-major order is more common).

独立的程序共享的共享内存段各分配自己的指数矩阵使用的malloc - 只有实际的数组分享。

Separate programs sharing the shared memory segment each allocate their own index matrix using malloc - only the actual array is shared.

顺便说一句,你可以用同样的方法对非共享阵列,搭配素色代替共享内存调用的malloc()。这使您可以使用一个分配整个阵列,加上一个指数,而你的code有一个分配的每列

By the way, you can use the same method for a non-shared array, replacing the shared memory call with a plain malloc(). This allows you to use a single allocation for the entire array, plus one for the index, whereas your code has one allocation per column.

这篇关于怎样的shmget和SHMAT在C双数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:46