disregard: sizeof struct returning unexpected results

S

Sean

I perused the archives of comp.lang.c and found some answers related
to addressability of struct elements (only in arrays?), and will
probably proceed by using byte or char arrays filled with raw data and
then converting to the expected types. Unless anyone has any helpful
or enlightening comments, I will leave this issue closed for now.

Thanks again for the time!
 
J

Jack Klein

I perused the archives of comp.lang.c and found some answers related
to addressability of struct elements (only in arrays?), and will
probably proceed by using byte or char arrays filled with raw data and
then converting to the expected types. Unless anyone has any helpful
or enlightening comments, I will leave this issue closed for now.

Thanks again for the time!

No, it has nothing at all to do with whether you define a single item
of a type or an array of them. The distance between one member of an
array of type T and the next is sizeof(type T), and the size of a
free-standing object of type T is also sizeof(type T).

Using an array of unsigned chars is a good idea, but be careful about
"converting" to the "expected" types. On some platforms the alignment
imposed by the compiler is required by the underlying processor
hardware, and violating it can have serious consequences.

Assuming sizeof(short) is 2 and sizeof(int) is 4, then you could use
something like this to pass the data around:

unsigned char data [6];

But this is a bad idea:

unsigned short us;
unsigned int ui;
unsigned char data [6];

/* get data into 'data' */

us = *(unsigned short *)data;
ui = *(unsigned long *)(data + 2);

....on some processors this produces code that runs more slowly but
correctly. On others, including newer RISC architectures, either you
get the wrong value or a hardware trap that terminates the program.

The safe way to transfer the data is:

memcpy(&us, data, 2);
memcpy(&ui, data + 2, 4);
 

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

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top