views:

117

answers:

2
struct struct0 {
  int a;
};

struct struct1 {
  struct struct0 structure0;
  int b;
} rho;


&rho->structure0; /* Reference 1 */
(struct struct0 *)rho; /* Reference 2 */
(struct struct0)rho; /* Reference 3 */
  1. From reference 1, does the compiler take the address of rho, and then access structure0, or vice-versa?

  2. What does the line at reference 2 do?

  3. Since structure0 is the first member of struct1, would reference 3 be equivalent to reference 1?

+4  A: 

In order of your references:

  1. the -> has higher precedence than the &. You're going to get the address of rho->structure0. Or rather, you would if rho were a pointer. Since it's not, you'll get a compile error.
  2. That won't work - you're casting a structure to a pointer type - you should get compiler error doing that.
  3. You can't do that either. A typecast to a non-scalar type is also an error.

Your examples #2 and #3 are covered by the standard section 6.5.4:

Unless the type name specifies a void type, the type name shall specify qualified or unqualified scalar type and the operand shall have scalar type.

If you put any of that code in a compiler you'd see the same results; is the code you're showing not what you intended to ask about?

Carl Norum
If the first member of rho was a pointer, would references 1 and 2 be equivalent?
Yktula
@Yktula, no, they still wouldn't work. `rho` itself needs to be a pointer to try any of that stuff.
Carl Norum
You're right. struct s1 { struct { int n } *s0; } *s1; main() { ( return 0; } prints Yes. Thank you.
Yktula
+2  A: 
&rho->structure0; /* Reference 1 */
(struct struct0)rho; /* Reference 3 */
(struct struct0 *)rho; /* Reference 2 */

All the three reference is not right:

  • rho is not a pointer. So you can not do rho->structure0 but (&rho)->structure0
  • You can not convert a variable to a pointer, so you can not do (struct struct0)rho; but (struct struct0 *)&rho

I quite dont really understand what you want to do, so I can not help you much.

Phong