¿Eres nuevo? ¡Lee el FAQ y ponte al día!
3k visitas

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:

C
  1. int rows = 10; // The number of rows of the 2D array
  2. int columns = 30; // The number of columns of the 2D array
  3. int row, column;
  4. int *matrix;
  5.  
  6. // Create the shared memory segment
  7. id_shmem = shmget(ipc_key, sizeof(int)*rows*columns, IPC_CREAT|0666);
  8.  
  9. // Attach the shared memory to our matrix
  10. matrix = (int *)shmat(id_shmem, 0, 0);
  11.  
  12. // Loop through all elements in the array
  13. for (row = 0; row < rows; row++)
  14. {
  15.     for (column = 0; column < columns; column++)
  16.     {
  17.         matrix[row*columns + column] = 1; // Equivalent to matrix[column][row]
  18.     }
  19. }
  20.  

­

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.

Etiquetas: C ipc shared memory

Insertar: