3

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!

qingy2019
  • 536
  • 7
  • 23
leo
  • 101
  • 6
  • 2
    Like it says, if the array size isn't constant you can't use an initializer. You'll have to write a loop: `for (int i = 0; i < c; i++) Pointer[i]=NULL;`. Or use `memset` if your platform has NULL pointers as all-bits-zero (most do). – Nate Eldredge Apr 25 '21 at 15:20
  • @NateEldredge Thanks Nate - I tried memset, it worked!! Thank you - One thing I do not understand, even if I made C as Const int, it still doesn't work. Is that normal.? – leo Apr 25 '21 at 15:24
  • Yes, that's normal. Just part of the somewhat peculiar way that C treats `const`. C++ is different. – Nate Eldredge Apr 25 '21 at 15:33

2 Answers2

4

You need to make a loop to initialize the array:

for (int i = 0; i < c; i++)
    Pointer[i] = NULL; // set all of these values to NULL

Now, Pointer will be of size c.

Also, this link may help, too: Array[n] vs Array[10] - Initializing array with variable vs real number

qingy2019
  • 536
  • 7
  • 23
2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Hey Vlad - I think you are right - By using memset(), it somehow initialized another array....is there anyway to fix it? – leo Apr 25 '21 at 16:32
  • @leo: That won't happen if you use `memset` correctly, so you must have a bug somewhere. You could ask it as a new question, but be sure to include a [mcve]. – Nate Eldredge Apr 26 '21 at 01:33