Why does this work? pointer = (struct a *) & b;

2
struct a {
    int a;
    int b;
};

struct b {
    int a;
    int b;
};

struct a *ponteiroa;
struct b b;

b.b = 20;

ponteiroa = &b; //Isto não dá certo
ponteiroa = (struct a *)&b; 

Why does this (struct a *)&b work? Why can the program do the assignment, even if it is a different structure?

    
asked by anonymous 19.09.2018 / 23:59

1 answer

8

I could answer that it is because C is a poorly typed language, it tries to make it work, even if it gives unexpected results. But as it is static typing does not accept the type be different, so if you are saying that the type is suitable the compiler accepts. And you did this when you indicated a coercion with the cast (struct a *) operator, so for all purposes you're throwing a structure to another and it's your problem whether the result will be good or not. You did compile, but nothing guarantees you'll be right. In the case we see that it will give because despite different names the structure is the same.

But in this particular case it is even simpler because both are pointers and all pointers are compatible (all are a simple memory address and it is universal), the object they point to is that they may not be, but in this case it is also. In any case you need to tell the compiler that you want to do this yourself, because he thinks he can give a problem and prevents, unless you are explicit, like he was through cast . >     

20.09.2018 / 00:07