Reputation: 2931
Getting an odd error trying to initialise an array in C - anyone know why this might happen?
I have a global variable:
static my_type foo[6];
And in an included header file, I have:
typedef uint32_t my_type[5];
I then in a function in the same file as the global variable try to do:
foo = {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 6}, {1, 2, 3, 4, 7}, {1, 2, 3, 4, 8}, {1, 2, 3, 4, 9}, {1, 2, 3, 4, 10}};
The compiler (GCC4) gives the error 'expected expression before '{' token'.
Anyone know what's gone wrong and how to fix it?
Cheers!
Upvotes: 2
Views: 112
Reputation: 41065
If you are under C99:
ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C89 mode and in C++.
But foo
must be a pointer
#include <stdio.h>
#include <stdint.h>
typedef uint32_t my_type[5];
int main(void)
{
int i, j;
my_type *foo;
foo = ((my_type[]) {
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 6},
{1, 2, 3, 4, 7},
{1, 2, 3, 4, 8},
{1, 2, 3, 4, 9},
{1, 2, 3, 4, 10}
});
for (i = 0; i < 6; i++) {
for (j = 0; j < 5; j++) {
printf("%d ", foo[i][j]);
}
printf("\n");
}
return 0;
}
Upvotes: 4
Reputation: 363858
That's not initialization, that's assignment. Initialization has to be a single statement:
static my_type foo[6] = {{1, 2, 3, 4, 5},
{1, 2, 3, 4, 6},
{1, 2, 3, 4, 7},
{1, 2, 3, 4, 8},
{1, 2, 3, 4, 9},
{1, 2, 3, 4, 10}};
You cannot assign to a whole array in C89 with this syntax. What you can do is memcpy
from a const
:
void initialize_foo()
{
static const my_type init[6] =
{{1, 2, 3, 4, 5},
{1, 2, 3, 4, 6},
{1, 2, 3, 4, 7},
{1, 2, 3, 4, 8},
{1, 2, 3, 4, 9},
{1, 2, 3, 4, 10}};
assert(sizeof(foo) == sizeof(init));
memcpy(foo, init, sizeof(foo));
}
Upvotes: 4