Simon
Simon

Reputation: 424

Memory placement of members in a struct

For me this piece of code was unexpected. I would previously in my naivity assume that members of a struct that a decleared in order was placed as,

| b1 | b2 | b3 | b4 |
first     second

but I think this snippet show that assumption to be false,

#include <assert.h>
#include <stdint.h>

typedef union {
    struct {
        uint16_t first;
        uint16_t second;
    };
    uint32_t id;
} uuid_t;

int
main(void)
{
    uuid_t uuid;
    uuid.id = 0x11112222;

    assert(uuid.first == 0x1111);
    assert(uuid.second == 0x2222);
}

With the correction,

typedef union {
    struct {
        uint16_t second;
        uint16_t first;
    };
    uint32_t id;
} uuid_t;

asserts will pass and that doesn't yet makes sense to me. Why is that?

Upvotes: 0

Views: 48

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

This seems because little-endian is used in your environment.

In little-endian environment, the number 0x11112222 is stored in memory like

 <--low      high-->
| 22 | 22 | 11 | 11 |

and the structure

struct {
    uint16_t first;
    uint16_t second;
};

probably be

 <--low      high-->
| 22 | 22 | 11 | 11 |
| first   | second  |

Therefore uuid.first will be 0x2222 and uuid.second will be 0x1111 by uuid.id = 0x11112222; in the first code.

Upvotes: 2

Related Questions