Difference between structures cast

Asked

Viewed 107 times

3

struct a{

   int a;
   int b;
};

struct b{

  int a;
  int b;

}

int main()
{

   struct a *p;

   struct b b;

  p = (struct a *)b; // deste modo da erro

  p = (struct a *)&b; ; deste modo o compilador não aponta erro;

}

I’d like to know why?

  • Did the answer solve the problem? Do you think you can accept one of them? See [tour] how to do this. You’d be helping the community by identifying the best solution. You can only accept one of them, but you can vote for anything on the entire site.

1 answer

2

(struct a *)b is taking a structure and making a cast for a pointer to a structure. This is not possible. A pointer is something very different from a structure.

In this case you are trying to put a structure with two integers inside a pointer and it does not fit. The main point of the type struct a * is that it is a pointer. What it points to is important, but secondary, primarily is a pointer.

(struct a *)&b is picking up an address for a structure, which is a pointer and making a cast for a pointer to a structure, this is possible. Are incompatible types, is pointer to pointer.

The & is the operator that picks up the address of something, that is, it generates a data that potentially will be a pointer, but will never be a structure.

Browser other questions tagged

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