I can successfully cast a pointer to a struct of 2 floats to a void pointer (used to discard incompatible pointer types warning), and then cast that to a float array and use that normally, however it doesn't seem to work in reverse with memcpy().
Say I have the following
struct {
float x;
float y;
} s;
float f[2][1] = {{6}, {3}};
I notice that if I use memcpy() to copy f to s
memcpy(&s, f, sizeof(f));
f[0][0] and f[1][0] are both 0. Intuitively I would expect it to do the same as
s.x = f[0][0];
s.y = f[1][0];
Why does this not work?
EDIT: I have been asked for more complete code:
void add(const float a[2][1], float b, float dest[2][1])
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 1; j++)
{
dest[i][j] = a[i][j] + b;
}
}
}
void predict(struct State *x, float u)
{
float buffer[2][1];
add(x, u, buffer); // Incompatible pointer types, but it works.
x->x = buffer[0][0];
x->y = buffer[1][0];
//memcpy(x, buffer, sizeof(buffer)); // doesn't work
}
The array layout is
The struct layout is
How big the padding fields are in bytes depends on the compiler.
The padding may be zero bytes (and typically will be zero bytes) in which case the layout is the same.
But from a standard point of view your code has undefined behavior because the array and the struct may have different size.