C method for iterating through a struct's members like an array?

zeboidlund picture zeboidlund · Jan 19, 2013 · Viewed 24.1k times · Source

Let's say I have a vector class:

typedef struct vec3_s
{
    float x, y, z;
}
vec3;

But, I would like to be able to iterate through it without converting it to an array of floats. While a cast is acceptable in this case, I'm curious to see if anything along the lines of C++ like functionality is doable in straight C. For example, in C++, since std::vector< T > has the subscript [] operator overloaded, I can pass the address of its first index to a function taking a void*.

i.e.,

void do_something_with_pointer_to_mem( void* mem )
{
    // do stuff
}

int main( void )
{
    std::vector< float > v;

    // fill v with values here

    // pass to do_something_with_pointer_to_mem

    do_some_with_pointer_to_mem( &v[ 0 ] );

    return;
}

Another, more concrete example is when calls to glBufferData(...) are made in OpenGL (when using C++):

glBufferData( GL_ARRAY_BUFFER, sizeof( somevector ), &somevector[ 0 ], GL_STREAM_DRAW );

So, is it possible to accomplish something similar in C using the subscript operator? If not, and I had to write a function (e.g., float vec3_value_at( unsigned int i )), would it make sense to just static inline it in the header file it's defined in?

Answer

greydet picture greydet · Jan 19, 2013

If all of your structure fields are of the same type, you could use a union as following:

typedef union vec3_u
{
    struct vec3_s {
        float x, y, z;
    };
    float vect3_a[3];
}
vec3;

This way you could access to each x, y or z field independently or iterate over them using the vect3_a array. This solution cost nothing in term of memory or computation but we may be a bit far from a C++ like solution.