1

I have a constant array that comes from a define that I cannot modify.

#define MY_ARRAY {1,11,111,2,22,222,3,33,333}
#define SIZE 3

I want to assign this array to a const struct array

// EDIT : Added mixed sizes to show there might be a padding problem as well
struct foo {
    uint8_t val1; 
    uint32_t val2;
    uint32_t val3;
}

const struct foo my_foo[SIZE] = MY_ARRAY;

But my compiler complains about missing braces around initializer. It expects something alongs the lines of :

const struct foo my_foo[SIZE] = {{1,11,111},{2,22,222},{3,33,333}};

I would need some kind of typecast but I can't make it work

I tried this :

const struct foo my_foo[SIZE] = (const struct foo[SIZE]) MY_ARRAY;

But I get the same warning

1 Answers1

0

In this situation, you could probably use a pointer cast:

const int[SIZE * 3] numbers = MY_ARRAY;
const struct foo my_foo[SIZE] = *(*my_foo[])&numbers;
PoolloverNathan
  • 148
  • 2
  • 11
  • This does not work https://godbolt.org/z/vaoE9781a – Joel Aug 29 '23 at 16:22
  • 3
    this is probably undefined behaviour because the `struct foo` has very likely a padding word so that `sizeof numbers != sizeof my_foo` – ensc Aug 29 '23 at 16:24
  • my real struct does contain mixed types so padding might be a problem yeah – john_hatten2 Aug 29 '23 at 16:48
  • @ensc It would also be a [strict aliasing violation](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) and UB for that reason, too. – Andrew Henle Aug 29 '23 at 16:51