Initialized a pointer array in C - Variable sized object may not be initialized

Viewed 239

I was trying to initialise a array made by pointer:

the code I used was:

int c = 15;
Struct *Pointer[c] = {NULL};

but C give me a error message which says:

"message": "variable-sized object may not be initialized",

but when I change my code to:

Struct *Pointer[15] = {NULL};

it worked!

Is there any way to fix it? I can't use 15 instead of variable "c"

Cheers!

2 Answers

Variable length arrays may not be initialized in their declarations.

You can use the standard string function memset to initialize the memory occupied by a variable length array.

For example

#include <string.h>

//...

int c = 15;
Struct *Pointer[c];

memset( Pointer, 0, c * sizeof( *Pointer ) );

Pay attention to that variable length arrays shall have automatic storage duration that is they may be declared in a function and may not have the storage specifier static.

Related