I have a struct for holding a 4D vector
struct {
float x;
float y;
float z;
float w;
} vector4f
And I'm using a library that has some functions that operate on vectors but take float pointers as their arguments.
Is it legal to call something like doSomethingWithVectors( (float *) &myVector)
?
A structure is a data type in C/C++ that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member.
An array of structures is simply an array in which each element is a structure of the same type. The referencing and subscripting of these arrays (also called structure arrays) follow the same rules as simple arrays.
Array size is fixed and is basically the number of elements multiplied by the size of an element. Structure size is not fixed as each element of Structure can be of different type and size.
Structure due to use defined data type become slow in performance as access and searching of element is slower in Structure as compare to Array. On other hand in case of Array access and searching of element is faster and hence better in performance.
You can write code that would make an attempt to treat it as an array, but the language makes no guarantees about the functionality of that code. The behavior is undefined.
In C language taking a storage region occupied by a value of one type and reinterpreting it as another type is almost always illegal. There are a few exceptions from that rule (which is why I said "almost"), like you can reinterpret any object as a char array, but in general it is explicitly illegal.
Moreover, the possible dangers are not purely theoretical, and it is not just about the possible alignment differences between arrays and structs. Modern compilers might (and do) rely on the aforementioned language rule in order to perform aliasing optimizations (read about strict aliasing semantics in GCC, for one example). In short, the compler is allowed to translate code under the assumption that memory occupied by a struct
can never overlap memory occupied by an array of float
. This often leads to unexpected results when people start using tricks like in your post.
It might work but it is not portable, the compiler is free to align things so that one float does not neccessarily immediately follow the other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With