Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I treat a struct like an array?

Tags:

c

pointers

vector

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)?

like image 989
spencewah Avatar asked Dec 27 '09 22:12

spencewah


People also ask

Can a struct be an array?

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.

How a structure can be used as an array?

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.

Is struct same as array?

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.

Is array better than structure?

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.


2 Answers

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.

like image 55
AnT Avatar answered Nov 05 '22 03:11

AnT


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.

like image 43
President James K. Polk Avatar answered Nov 05 '22 03:11

President James K. Polk