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!

3
  • 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). Commented Apr 25, 2021 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.? Commented Apr 25, 2021 at 15:24
  • Yes, that's normal. Just part of the somewhat peculiar way that C treats const. C++ is different. Commented Apr 25, 2021 at 15:33

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Hey Vlad - I think you are right - By using memset(), it somehow initialized another array....is there anyway to fix it?
@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 minimal reproducible example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.