struct Vector
{
float x, y, z;
};
func(Vector *vectors) {...}
usage:
load float *coords = load(file);
func(coords);
I have a question about the alignment of structures in C++. I will pass a set of points to the function func(). Is is OK to do it in the way shown above, or is this relying on platform-dependent behavior? (it works at least with my current compiler) Can somebody recommend a good article on the topic?
Or, is it better to directly create a set of points while loading the data from the file?
Thanks
Structure alignment is implementation-dependent. However, most compilers give you a way of specifying that a structure should be “packed” (that is, arranged in memory with no padding bytes between fields). For example:
The above code will cause the gcc compiler to pack the structure in memory, making it easier to dump to a file and read back in later. The exact way to do this may be different for your compiler (details should be in your compiler’s manual).
I always list members of packed structures on separate lines in order to be clear about the order in which they should appear. For most compilers this should be equivalent to
float x, y, z;but I’m not certain if that is implementation-dependent behavior or not. To be safe, I would use one declaration per line.If you are reading the data from a file, you need to validate the data before passing it to
func. No amount of data alignment enforcement will make up for a lack of input validation.Edit:
After further reading your code, I understand more what you are trying to do. You have a structure that contains three
floatvalues, and you are accessing it with afloat*as if it were an array of floats. This is very bad practice. You don’t know what kind of padding that your compiler might be using at the beginning or end of your structure. Even with a packed structure, it’s not safe to treat the structure like an array. If an array is what you want, then use an array. The safest way is to read the data out of the file, store it into a new object of typestruct Vector, and pass that tofunc. Iffuncis defined to take astruct Vector*as an argument and your compiler is allowing you to pass afloat*without griping, then this is indeed implementation-dependent behavior that you should not rely on.