简体   繁体   中英

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

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!

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM