I have structure table that I want to initialize in the beginning of my program
typedef struct MyStructT{
int Output;
int Input1;
int Input2;
};
int n=100;
MyStructT Table[n] = ?? ;
How do I do it?
I have structure table that I want to initialize in the beginning of my program
typedef struct MyStructT{
int Output;
int Input1;
int Input2;
};
int n=100;
MyStructT Table[n] = ?? ;
How do I do it?
You can't do this using array initialisation since n
is not known at compile time; i.e. you have a variable length array.
One way is to loop over each element of the struct
array, and initialise the members manually. It'll pop out nicely in a few lines.
Alternatively, given that the C standard guarantees contiguity of the struct
elements, and memset
to 0 is a well-defined way of initialising a C struct
, you could memset
the entire array:
memset (Table, 0, n * sizeof(struct MyStructT));
Since you have:
int n = 100;
MyStructT Table[n];
you have a VLA — variable length array. You cannot initialize VLAs. Period. You have to write code to set them to an initial value, somehow.
The standard (ISO/IEC 9899:2011 — C11) says in §6.7.9 Initialization:
¶3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.
Note that changing n
to const int n = 100;
doesn't help in C (though it would in C++ — but C++ doesn't support VLAs anyway, despite GCC allowing them).
If the requirement is to set the elements to all bytes zero, then you could write:
memset(Table, '\0', sizeof(Table));
which will do the job. Note that the value of sizeof(Table)
is evaluated at runtime because Table
is a VLA.
Alternatively, if you don't really need a VLA, change the array bound to an enum
or #define
constant and then you can initialize the array using the normal techniques.