Sunday, 8 September 2013

Memory content behind C struct pointers

Memory content behind C struct pointers

Browsing through some old C code, and I came across this snippet. I am
thoroughly confused as to what is happening behind the scenes.
I don't have a full understanding of struct pointer usage and operability,
and I can't quite understand how the memory is being stored and accessed
in the following code.
struct x{
int i1;
int i2;
char ch1[8];
char ch2[8];
};
struct y{
long long int f1;
char f2[18];
};
int main(void)
{
struct x * myX;
struct y * myY;
myX = malloc(sizeof(struct x));
myX->i1 = 4096;
myX->i2 = 4096;
strcpy(myX->ch1,"Stephen ");
strcpy(myX->ch2,"Goddard");
myY = (struct y *) myX;
printf("myY->f1 = %d\n", myY->f1);
printf("myY->f2 = %s\n", myY->f2);
}
This outputs
myY->f1 = 4096
myY->f2 = Stephen Goddard
After the cast, i1 is stored into myY->f1 and both ch1 & ch2 is stored in
myY->f2. My question is how?. What does the memory content look like after
the cast?
I know it has to do with the size of the struct and where the pointer is
pointing (obviously), but after looking at this code, it has definitely
made me realize my lack of understanding pointers.
Thank you

No comments:

Post a Comment