So im having this problem that I want to add "one" structure and one int to my shared memory And I want to have my "int in the first position of the shared memory" (since i ll need this int in another programs) and then have the structure This is my code
int id = shmget( 0x82488, (sizeof(student)) + sizeof(int) ,IPC_CREAT | 0666 );
exit_on_error (id, "Error");
int *p = shmat(id,0,0);
exit_on_null(p,"Erro no attach");
Student *s = shmat(id,0,0);
exit_on_null (s,"Error");
And now comes my question since I have 2 pointers how can I make the int be the first and then the structure, should I just
p[0]=100 s[1] = (new Student)
I would just do
int *p = shmat(id,0,0);
exit_on_null(p,"Erro no attach");
Student *s = (Student*)(void*)(p + 1);
so that s
points to where the next int would be if that would be an int.
It is a bit tricky, but clears all possible interoperation issues with possible padding bytes in a struct.
Example:
+---+---+---+---+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+---+---+---+---+---+---+---+---+---+---+
In this case, p
points to the location 0 (relative to the start of the buffer), and thus p + 1
points to the position 4 (if an int
has 32 bits). Casting p + 1
the way I do makes pont s
to this place, but be of type Student *
.
And if you want to add a structure struct extension
, you do the same:
struct extension *x = (struct extension*)(void*)(s + 1);
This points immediately behind the Struct
and, again, has the correct pointer type.
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.