How to use multidimensional arrays in shared memory with IPC
Since you should not store pointers in shared memory (the memory addresses are different for different processes), you can not create multidimensional arrays in the "traditional" way (int **, for instance). The solution to this is to emulate the multidimensional array with index magic.
In the following example a 2D array of integers is created in shared memory with IPC. Then, it is shown how to access the different positions of the array:
- int rows = 10; // The number of rows of the 2D array
- int columns = 30; // The number of columns of the 2D array
- int row, column;
- int *matrix;
- // Create the shared memory segment
- id_shmem = shmget(ipc_key, sizeof(int)*rows*columns, IPC_CREAT|0666);
- // Attach the shared memory to our matrix
- matrix = (int *)shmat(id_shmem, 0, 0);
- // Loop through all elements in the array
- for (row = 0; row < rows; row++)
- {
- for (column = 0; column < columns; column++)
- {
- matrix[row*columns + column] = 1; // Equivalent to matrix[column][row]
- }
- }
This way, you can work with shared memory as if it was a multidimensional array. In general, if you want to access the (x, y) position, you use the following formula: y*width + x.
Enviado por miguelSantirso hace over 2 years — modificado por última vez hace less than a minute