strange about struct in c

J

J Wang

typedef struct {
unsigned short int type; /* Magic identifier
*/
unsigned int size; /* File size in bytes
*/
unsigned short int reserved1, reserved2;
unsigned int offset; /* Offset to image data, bytes
*/
} HEADER

when I use HEADER to define a struct header,
the sizeof(HEADER) is 16. it should be 14, in my machine SunOS5.8.

and I check each member memory address in struct HEADER, there is a leap
between first member and second one, i.e.,
header.type is 0xffb887e0
header.size is 0xffb887e4.

I also check the sizeof(header.type) is 2

how to deal with it? I want to build the bitmap format. so the leap memory
should be useful. how to explain it?

many thanks
 
J

Jens.Toerring

J Wang said:
typedef struct {
unsigned short int type; /* Magic identifier
*/
unsigned int size; /* File size in bytes
*/
unsigned short int reserved1, reserved2;
unsigned int offset; /* Offset to image data, bytes
*/
} HEADER
when I use HEADER to define a struct header,
the sizeof(HEADER) is 16. it should be 14, in my machine SunOS5.8.

It shouldn't be 14. The compiler is allowed to put as many padding
bytes in between the elements as it thinks are needed. Probably on
your architecture only memory accesses to entities that are 4 byte
wide are allowed for addresses that can be divided by 4 - without
the padding you would get a bus error or something similar on
assignments otherwise.

If you need a memory layout like this with only 14 bytes then use
a simple char array and memcpy() the data into it - memcpy() is
supposed to get it right for whatever restrictions on the machine
exist.
Regards, Jens
 
E

Eric Sosman

J said:
typedef struct {
unsigned short int type; /* Magic identifier
*/
unsigned int size; /* File size in bytes
*/
unsigned short int reserved1, reserved2;
unsigned int offset; /* Offset to image data, bytes
*/
} HEADER

when I use HEADER to define a struct header,
the sizeof(HEADER) is 16. it should be 14, in my machine SunOS5.8.

and I check each member memory address in struct HEADER, there is a leap
between first member and second one, i.e.,
header.type is 0xffb887e0
header.size is 0xffb887e4.

I also check the sizeof(header.type) is 2

how to deal with it? I want to build the bitmap format. so the leap memory
should be useful. how to explain it?

many thanks

This is Question 2.12 in the comp.lang.c Frequently
Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top