简体   繁体   English

在 C 中初始化了一个指针数组 - 可变大小的 object 可能未初始化

[英]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:但 C 给我一条错误消息,上面写着:

"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"我不能使用 15 代替变量“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 .现在, Pointer的大小将是c

Also, this link may help, too: Array[n] vs Array[10] - Initializing array with variable vs real number此外,此链接也可能有所帮助: Array[n] vs Array[10] - Initializing array with variable vs real number

Variable length arrays may not be initialized in their declarations.可变长度 arrays 可能未在其声明中初始化。

You can use the standard string function memset to initialize the memory occupied by a variable length array.可以使用标准字符串 function memset来初始化变长数组占用的 memory。

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 .请注意,可变长度 arrays 应具有自动存储持续时间,即它们可以在 function 中声明,并且可能没有存储说明符static

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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