Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Struct question

Status
Not open for further replies.

sbayeta

Programmer
Apr 4, 2003
13
0
0
AR
I have a struct in my program with several fields in it. I'd like to know if those fields are guaranteed to be in the order I declared them if I read the struct using an unsigned char *ptr:

struct datastruct {
int i;
long l;
float f;
char c[4];
} mydata;

I'll be wirting this data with a function declared as

write_data(unsigned int address, unsigned char *data, unsigned char size);

And the call would be

write_data(address, (unsigned char*)&mydata, sizeof(mydata));

I need to be shure that my data will be written in the same order I declared it in the struct.

My compiler is little-endian, and claims to be full ANSI C compliant.

Thanks in advance.
 
On the same platform you can do this.
Also you can have holes (padding) inside or at the end of structure. You still should be fine if you will read saved data back in the same structure and do not try to read value of one field based on shift.
 
> write_data(unsigned int address, unsigned char *data, unsigned char size);
Why not
Code:
write_data(unsigned int address, void *data, unsigned char size);

or better,

Code:
write_data(unsigned int address, const void *data, unsigned char size);

This will save you having to cast your pointer everytime you want to save some data.

Just to add to what Lim has said about padding.
Writing raw data structures out to disk is highly non-portable. You will almost certainly run into trouble if you try and read that file written by another copy of the program compiled for a different OS, with a different compiler. It is conceivable that just changing the compiler options of your current compiler could alter the alignment of data within your structure.

For example, gcc has -malign-double which changes the alignment of doubles from 4 bytes to 8 bytes.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top