I have a question regarding the initialization of an array of structs in C. Googling showed me that a lot of people have had very similar questions, but they weren’t quite identical.
Essentially, I have a global array of structs of type “memPermissions” shown below.
This array needs all the “address” and “ownerId” fields to be initialized to -1 upon program execution.
typedef struct memPermissions {
int address;
int ownerId;
} *test;
The problem is the array is sized using a #define, so I can’t simply go:
#define numBoxes 5
struct memPermissions memPermissions[numBoxes] = {
{-1, -1},
...
{-1, -1}
};
I tried:
struct memPermissions memPermissions[numBoxes] = {-1, -1};
But naturally this only initialized the first element. (The rest were set to 0). The only solution that jumps to mind would be to initialize it with a simple loop somewhere, but because of the nature of where this code will run, I’m really hoping that’s not my only option.
Is there any way to initialize all the elements of this array of structs without a loop?
Cheers,
-Josh
Which is the only possibility within the language, I’m afraid. In C, you either initialize each element explicitly, initialize to all zeros or don’t initialize.
However, you can sidestep the issue by using
0for the purpose that your-1currently serves.