hicham ATR hicham ATR - 3 months ago 9
C Question

What is the meaning of a struct variable's name?

What is the meaning of the struct variable's name?

In other words, when i tried code :

typedef struct enr
{
int a ;
char b ;
}enr ;

int main()
{
enr x ;
printf(" x = %d\n",x) ;
printf(" x.a = %d\n",x.a);
return 0 ;
}


I get : 38 for x and a.x both ! so I get the first field of the structure as a content of x.

Can any one tell me what's happen in the general case (when the first variable was an array, char, or something else)?

Answer

C has no knowledge of structure member types at runtime. But you told it what the type was with the "%d" in your printf. It printed the value of the integer at x.a not because a was declared to be an integer, but because you told it to. Likewise, x without the member refers to the structure as a whole, but since its address is the same as the address of its first member, and you told it to look for an int there, it found one. If your printfs had used "%f", it would have printed a floating point number represented by the bits at that address for both expressions.