Interesting and useful . .
In both C and C++, a struct is laid out flat in memory, just like an array is.
‘Course, this means that you can treat a struct as an array, without ever using a union.
The next example shows how.
#include <iostream>
using namespace std;
struct Vertex
{
float x,y,z;
};
int main()
{
Vertex v;
v.x = 2.0f, v.y = 1.0f, v.z = 5.0f;
// print each member of the struct
printf( "v: %f %f %f\n", v.x, v.y, v.z );
// now treat as an array
float * arr = &(v.x); // get the address of v.x
// since v is laid out flat in memory, just like an array
// this will work out fine
// struct Vertex laid out flat in memory, like
// this, so accessing it as an array is no problem
// ___________________
// | | | |
// | 2.0 | 1.0 | 5.0 |
// |_____|_____|_____|
// x y z
for( int i = 0; i < 3; i++ )
{
printf( "v[%d]: %f\n", i, arr[i] );
}
}
Incidently, this is the same way you would access a C++ STL vector’s internals as a regular C++ array.
Something like:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
v.push_back( 2 );
v.push_back( 5 );
v.push_back( 7 );
// now normally, you may think
// its fine to just go through
// the elements of v like this:
printf("Using [] operator on v:\n");
for( int i = 0; i < v.size(); i++ )
{
printf("v[%d]: %d\n", i, v[i] );
}
// And it IS fine, mostly.
// However, sometimes you're working with a
// C API that wants a REGULAR int * pointer
// to an array, and won't accept an STL
// vector.
// What's one to do? Stop using STL vectors??
// No!! :).
// You can get a regular (type *) C-style array
// pointer to the internals of any STL vector:
int * internalsPointer = &v[0];
int length = v.size();
printf("\n\nUsing internalsPointer\n");
for( int i = 0; i < length; i++ )
{
printf("v[%d]: %d\n", i, internalsPointer[i] );
}
// Its good if you need to pass the
// vector's internals to a function that wants
// a C-style array (e.g. OpenGL's vertex
// array funcs).
}