title: C Shared memory pointer mapping
body: <p>I have a data structure as follows:</p>
  
  <pre><code>struct s1{
  unsigned char* ptr;//points to an element in the shared memory
  };
  
  struct s1* s1Arr;
  </code></pre>
  
  <p>And I allocated a shared memory block and the pointer to it is:</p>
  
  <pre><code>unsigned char* shm_ptr.
  </code></pre>
  
  <p>I have an array of s1, with the same number of elements as there are elements in the shm_ptr array I allocated.</p>
  
  <pre><code>//point all the ptr elements of the struct to the shared memory elements(parallel array)
  for(i = 0; i &lt; count; i++)
  {
  shm_ptr[i] = 99;
  s1Arr[i].ptr = &amp;shm_ptr[i];
  printf("val=%d\n". *s1Arr[i].ptr);
  }
  </code></pre>
  
  <p>When I go to print *s1Arr[i].ptr, it only prints i, where i is 0, 1...while it should be printing 99.
  Any thoughts as to what I am doing wrong? </p>
  
  <p>I know the shared memory is working as I have tried to access it from another process.</p>
  
  <pre><code>void* allocArray_shared(int elementCount, int elementByteSize, int* shmid, key_t key)
  {
      printf("allocshared errno=%d\n", errno);
      //size of entire array(cols*rows* byte size + row pointers)
      int array_size = elementByteSize * elementCount;
  
  
      //Allocate enough space for all elements + row pointers
      *shmid = shmget(key, array_size, 0666 | IPC_CREAT);
  
      char * arr = (char*)shmat(*shmid, NULL, 0);
      if(!arr) return NULL;
  
      printf("allocshared end errno=%d\n", errno);
  
      //Return the pointer to the first row pointer
      return (void*)arr;
  }
  </code></pre>
  
  <p>EDIT:
  Found the issue..was allocating multiple shared memory segments with the same key and thus reads/writes were overlapping...ugh...</p>