简体   繁体   中英

Accessing a specific element on IPC shared memory

I'm reading about shared memory, and a question popped up in my head - since the signature of shmget is int shmget(key_t key, size_t size,int shmflg) then we can allocate for example a shared memory of 30 integers by passing 30*sizeof(int) as argument to shmget, so my question is can we access an nth element of that shared memory ? (can we access the 4th integer of our shared memory for example?)

Why don't you access it like you would do with a normal pointer ? For instance :

int shmid = shmget(key, 30 * sizeof(int), 0644 | IPC_CREATE);
void* data = shmat(shmid, (void *)0, 0);
int element = *((int *)data + 3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM