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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…