Casting array of structs containing floats to array of floats

tobeythorn 101 Jan 26, 2011 at 19:00

I am trying to get some c code I developed on a mac to work on my windows machine. In the code, I defined a struct to represent each vertex, containing 4 floats for vertex position (x, y, z, w), and 4 floats for the vertex normal vector (nx, ny, nz, nw). I then made an array of these structs and cast it to an array of floats to create a striped array of vertex data for use with a vertex buffer object in OpenGL. This worked fine in xcode (which uses clang compiler?).

On my windows machine, using mingw and gcc, when I print out the cast array in the console, I get garbage. I’m guessing my assumption that the floats inside the struct would be lined up nicely in memory and without padding is wrong under certain compilers. Is there a way to make this work?

3 Replies

Please log in or register to post a reply.

Reedbeta 167 Jan 26, 2011 at 19:15

That is bizarre. The floats should be lined up nicely in memory, without padding in gcc as well, AFAIK. Can you check the sizeof() on your struct? If it has 8 floats, it should be 32 bytes, whether on the Mac or in Windows.

_oisyn 101 Jan 26, 2011 at 20:41

Officially this is undefined behaviour. In practice, however, I can’t imagine any 32 bit compiler having problems with this. Can you post how you declare the structure and how you cast it to an array of floats?

tobeythorn 101 Jan 27, 2011 at 19:13

Thanks for your suggestions. I checked the size of my structs and indeed they are correct (32 bits for 8 floats), which led me to realize that I had made a embarrassingly dumb mistake when trying to print out out the cast array for debugging. The problem I’m having instead seems to be with sending the vertices to the vertex shader, so I’ll work on that.