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

Asked

Viewed 77 times

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 is this (struct a *)&b does it work? Why can the program, even though they are different structures, do the attribution?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

8

I could answer that is because C is a weakly 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 being different, so if you are saying that the type is suitable the compiler accepts. And you did that when you indicated a coercion with the cast (struct a *), so for all intents and purposes is throwing one structure to another and it is your problem whether the result will be good or not. You did compile, but nothing guarantees that it will be right. In this case we see that you will even 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, in this case it is also. In any case you need to indicate to the compiler that you want to do just that, because he thinks it can give a problem and prevents, unless you are explicit, as it was through the cast.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.