Search code examples
cmemoryunions

Dereferenced union member bytes are not the same


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) ?


Solution

  • 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 *)?