Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure pointer pointing to different structure instance

Tags:

c

pointers

struct

struct first_struct
{
    int a;
    int b;
};

struct second_struct
{
    char d;
    int e;
};

struct second_struct second_ins = {'a',10};
struct first_struct first_ins = {20,12};



int main()
{
    struct second_struct *pointer = &first_ins;
    printf("%d\n",pointer->d);   
    return 0;
}

And I get an output of 20. Basically, I was trying to see that if I declare a structure pointer, and try to point this to an instance of another structure, what result do I get. Besides a warning from compiler for an incompatible pointer type, it builds and runs fine. I was trying to understand how this operation was interpreted by compiler. Shouldnt this be undefined, or may be it is and I am just getting lucky with the result.

like image 729
SandBag_1996 Avatar asked Nov 01 '22 12:11

SandBag_1996


1 Answers

It's likely that both structs have the same element-wise alignment: sizeof(first_struct) == sizeof(second_struct) and: int e starts at the same offset in the struct as: int b

In other words, char d is effectively stored as an int in terms of layout. It's simply a lucky coincidence on your platform, and will not work portably.

like image 121
Brett Hale Avatar answered Nov 15 '22 06:11

Brett Hale