0

I am using a BIT filed varibale in a struct to Modify the size of the data type. I need this struct to be exactly equals 1. According to my calculations it is equal to 10 but when I use the sizeof() operator I get 12. How should I overcome this problem.

typedef uint8_t  BYTE;
typedef int32_t DWORD;
typedef uint32_t  LONG;
typedef uint16_t WORD;

typedef struct
{
     LONG id:24; //"ID3"
     WORD version; // $04 00
     BYTE flags; // %abcd0000
     LONG size; //4 * %0xxxxxxx
}ID3TAG;

1 Answer 1

1

You're getting 12 because of something called alignment, which adds internal padding to structures.

You can read more about it here:
http://c-faq.com/struct/align.html
https://en.wikipedia.org/wiki/Data_structure_alignment

A quick workaround for this would be to use __attribute__((__packed__)) like you've used in pset4 (see bmp.h there).

Like this:

#include <stdio.h>
#include <stdint.h>

typedef uint8_t  BYTE;
typedef int32_t DWORD;
typedef uint32_t  LONG;
typedef uint16_t WORD;

typedef struct
{
     LONG id:24; //"ID3"
     WORD version; // $04 00
     BYTE flags; // %abcd0000
     LONG size; //4 * %0xxxxxxx
} __attribute__((__packed__))
ID3TAG;

typedef struct
{
     LONG id:24; //"ID3"
     WORD version; // $04 00
     BYTE flags; // %abcd0000
     LONG size; //4 * %0xxxxxxx
}
ID3TAG_not_packed;


int main(void)
{
    printf("sizeof ID3TAG packed: %zu\n", sizeof(ID3TAG));
    printf("sizeof ID3TAG unpacked: %zu\n", sizeof(ID3TAG_not_packed));
}

OUTPUT:

sizeof ID3TAG packed: 10
sizeof ID3TAG unpacked: 12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .