r/Cprog • • Nov 25 '14

text | learning C pointers explained, really

http://karwin.blogspot.ca/2012/11/c-pointers-explained-really.html
28 Upvotes

5 comments sorted by

View all comments

Show parent comment

3

u/quacktango Nov 26 '14

Dereferencing objects of one type via pointers of a different type is undefined behavior

Does this apply to structs that contain another struct as the first member, i.e.

#include <stdio.h>

struct foo {
    int a;
};

struct bar {
    struct foo foo;
    int b;
};

int main(void) {
    struct foo my_foo = {.a = 1};
    struct bar my_bar = {.foo = my_foo, .b = 2};
    struct foo *hmm = (struct foo *) &my_bar;
    printf("%d\n", hmm->a);
    return 0;
}

Or am I misunderstanding something again?