Pointer vs array in C, non-trivial difference

Please forgive me if i overlook anything in your analysis. But i think the fundamental bug in all that is this wrong assumption

type2_p->ptr has type “pointer to int” and the value is the start address of my_test.

There is nothing that makes it have that value. Rather, it is very probably that it points somewhere to

0x00000001

Because what you do is to interpret the bytes making up that integer array as a pointer. Then you add something to it and subscript.

Also, i highly doubt your casting to the other struct is actually valid (as in, guaranteed to work). You may cast and then read a common initial sequence of either struct if both of them are members of an union. But they are not in your example. You also may cast to a pointer to the first member. For example:

typedef struct {
    int array[3];
} type1_t;

type1_t f = { { 1, 2, 3 } };

int main(void) {
    int (*arrayp)[3] = (int(*)[3])&f;
    (*arrayp)[0] = 3;
    assert(f.array[0] == 3);
    return 0;
}

Leave a Comment