0

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?

MrsIl
  • 53
  • 1
  • 5
  • Does it have to be a variable length array? If you can use a static or a global array (i.e. define it as at the compilation unit level, with a fixed `#define` length instead of `n`), it will be initialized to `0`. Otherwise just set it manually to `0` before using it. Note that local VLA variables are usually placed on the stack, so in embedded environments you might want to be careful how much you will allocate. – vgru Aug 04 '17 at 07:32

2 Answers2

3

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));
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278