------------------------------- Here is my
program------------------------------------------
#include <stdioi.h>
#include <stddef.h>
typedef struct dummy{
int x,y,z;
}point;
main() {
point a = {1,2,3};
int *p = (int *)(&a + offsetof(point, y);
int *q = (int *)(&a + offsetof(point, z);
printf("%d %d",*p,*q);
}
The behavior of your program is undefined. To explain why, it's easier
if I introduce two new objects:
point array[8];
point *pp = array;
Also, I will assume, in order to make my explanation more concrete, that
we're using an implementation where sizeof(int)==2, and puts no padding
in struct dummy. Then sizeof(point) == 6, offsetof(point,y)==2, and
offsetof(point, z)==4.
When you add an integer N to a pointer, it shifts that pointer by a
large enough amount memory to store N copies of the thing it points at.
Therfore, while pp currently points at array[0], pp+offsetof(point,y)
points at p[2]. pp+offsetof(point,z) points at array[4]. If converted to
(int*), those pointers would point at the 'x' members of those structures.
For the purposes of this rule, a single object is treated as an array of
length 1. Therefore, &a+offsetof(point,y) would, in principle, point at
a memory location that hasn't necessarily been reserved for use by your
program. That's why the behavior of your program is undefined.
To get the results you desire, you need to use:
int *p = (int*)((char*)&a + offsetof(point, y));
Since the sizeof(char)==1, adding N to a char* pointer moves it forward
by N bytes, which is what you are trying to do.
i ran this program on DevC++ 4.9.9.2 and i'm getting some garbage
values as output!
That's one of the plausible results from attempting to read memory that
you're not supposed to be reading.