Reputation: 41
I want to include a variable length two-dimensional array pointer as part of a struct, but the c99 compiler gives me the following error on the Array anArray
line: "flexible array member in otherwise empty struct".
typedef const int Array[][2];
typedef struct {
Array anArray;
} StructType;
Array myArray = {{1,2},{3,4},{5,6}};
StructType myStruct = { myArray };
I would appreciate any insight into this problem and the solution. I will eventually be adding other components to StructType
.
Upvotes: 1
Views: 881
Reputation: 2964
What you did without knowing is creating a struct with a flexible array member. Usually in C all members of structs and unions need to have complete types, i.e. their length must be exactly known at compile time. However, there is an exception for the last member that does not need to but instead becomes the "flexible array member". The problem in your case is that you do not have any other members in the struct, and this is not legal (I can't come up with a convincing rationale why this is atm). Storing a pointer in the struct is of course not equal to storing the complete array but it is probably more like what you want (at least as a beginner).
Upvotes: 1
Reputation: 41
Thanks for the comments. I changed the code to the following, and now it compiles.
typedef const int Array[][2];
typedef const struct {
int something;
Array *pAnArray;
} StructType;
Array myArray = {{1,2},{3,4},{5,6}};
StructType myStruct = { 0, &myArray };
Upvotes: 0
Reputation: 28850
The structure needs to know the size of the array, and here you're missing one dimension. If declaration and initialization were done at the same time, you could eg
int Array[][2] = {{1,2},{3,4},{5,6}};
then the compiler makes the space for the array and sets the value (otherwise that would have to be at run time, using dynamic allocation).
Secondly, in C unfortunately that practical way of initializing an array is not possible
StructType myStruct = { myArray };
That would have to be done at runtime (and C would have some trouble performing that kind of assignment in the case of dynamic allocation, for instance, since there is no mechanism to keep objects sizes up to date).
What you can do, though, is setting the size of the missing dimension, and copy the array thanks to the memory function memcpy
typedef const int Array[3][2];
typedef struct {
Array anArray;
} StructType;
int main(int argc, char **argv) {
Array myArray = {{1,2},{3,4},{5,6}};
StructType myStruct;
memcpy(myStruct.anArray,myArray,sizeof(myArray));
You can also do the structure declaration and initialization this way
StructType myStruct = { {{1,2},{3,4},{5,6}} };
and in C99, even
StructType myStruct = { .anArray = {{1,2},{3,4},{5,6}} };
Upvotes: 2