Reputation: 10585
From the tutorial at learnc, I am experimenting with some really basic stuff on pointers and unions. In the code below I create a struct operator
with an anonymous union
consisting of a float
, double
, and int
. Since double
is the biggest one at eight bytes, I expect to see my int
have eight bytes, which it does. However, they are not the same bytes as the double!
typedef enum {
INTEGER = 0,
FLOAT = 1,
DOUBLE = 2,
} operator_type;
typedef struct operator {
operator_type type;
union {
int intNum;
double doubleNum;
float floatNum;
};
} operator_t;
int main() {
operator_t op;
op.type = FLOAT;
op.floatNum = 3.14f;
printf("op.intNum = %i\nop.doubleNum = %f\nop.floatNum = %f\n", op.intNum, op.doubleNum, op.floatNum);
printf("op.intNum [%i, %i, %i, %i, %i, %i, %i, %i, %i]",
&(op.intNum) + 0,
&(op.intNum) + 1,
&(op.intNum) + 2,
&(op.intNum) + 3,
&(op.intNum) + 4,
&(op.intNum) + 5,
&(op.intNum) + 6,
&(op.intNum) + 7,
&(op.intNum) + 8
);
printf("op.doubleNum [%i, %i, %i, %i, %i, %i, %i, %i, %i]",
&(op.doubleNum) + 0,
&(op.doubleNum) + 1,
&(op.doubleNum) + 2,
&(op.doubleNum) + 3,
&(op.doubleNum) + 4,
&(op.doubleNum) + 5,
&(op.doubleNum) + 6,
&(op.doubleNum) + 7,
&(op.doubleNum) + 8
);
return 0;
}
I get the output:
op.intNum [-13304, -13300, -13296, -13292, -13288, -13284, -13280, -13276, -13272]
op.doubleNum [-13304, -13296, -13288, -13280, -13272, -13264, -13256, -13248, -13240]
Shouldn't &(op.intNum) == &(op.doubleNum) == &(op.floatNum)
?
Upvotes: 1
Views: 51
Reputation: 76
In your case you don't dereference union, for dereferencing you need to declare op as pointer.
FYI:
In your code you print
address of int member, and sizeof(int) is 4 in your architecture, so increment by 1 , your address will be address + sizeof(int)
address of double member and sizeof(double) in 8, in this case each after each increment your address will be address + 8
Hope this will help.
Upvotes: 0
Reputation: 11
&(op.intNum) + 1
is the address immediately after the end of op.intNum
.
That is, if op.intNum is at address A, and sizeof op.intNum is 4, then the expression you wrote has value A+4.
That's a consequence of how pointer arithmetic is defined.
Upvotes: 1
Reputation: 73376
Shouldn't
&(op.intNum)
==&(op.doubleNum)
==&(op.floatNum)
?
Yes, they should, and they are.
In order to print an address, use %p
as the format specifier, and cast it to void*
. Read more in How to print variable addresses in C?
Edit: Why do I have to cast my memory address to (void *)?
Upvotes: 1