I am working with shared memory and hence I need to attach some portion of the memory to some other process.
I am trying to attach to a contiguous sequence, but this does not seem to work after the integer and the float arrays.
Here NUMBER_OF_DATA=5
int shmid=shmget(key,size,0777|IPC_CREAT);
int *a=(int *)shmat(shmid,0,0);
float *b=(float *)(a+NUMBER_OF_DATA);
char *array1[20];
array1[0]=(char *)(b+NUMBER_OF_DATA);
char *array2[20];
array2[0]=(char *)(array1+(20*NUMBER_OF_DATA));
for(i=0;i<NUMBER_OF_DATA;i++)
{
a[i]=roll_no[i];
b[i]=cgpa[i];
array1[i]=firstname[i];
array2[i]=lastname[i];
printf("%p %p %p %p\n",&a[i],&b[i],&array1[i],&array2[i]);
}
When I print the addresses, I get
0xb777d000 0xb777d014 0xbfd480a0 0xbfd480f0
0xb777d004 0xb777d018 0xbfd480a4 0xbfd480f4
0xb777d008 0xb777d01c 0xbfd480a8 0xbfd480f8
0xb777d00c 0xb777d020 0xbfd480ac 0xbfd480fc
0xb777d010 0xb777d024 0xbfd480b0 0xbfd48100
which is not continuous after the arrays a and b. Why is this so? What is the solution?
You’re only initializing the first field of
array1andarray2, the rest is uninitialized. You seem to have confused something, but I’m not sure what you exact intention is here.If you want the two arrays to be
char *s, it’s simple, do it like you did it for the ints and floats.However, if you really want something like a
char*[], you need to store not just the values, but also the pointers to the values in the shared memory segment.