I have this code :
我有这个代码:
#define N 100 //starting size of the array
int is_full(VERTEX *arr);
int add_vertex(char *name);
int print_degree(int ID);
int _get_vertex(int ID);
VERTEX *resize_array(VERTEX *vertex_array,int new_size);
VERTEX *arr = (VERTEX*)calloc(N, sizeof(VERTEX)); // dynamic allocation and initialization to NULL
I have this code :
我有这个代码:
#define N 100 //starting size of the array
int is_full(VERTEX *arr);
int add_vertex(char *name);
int print_degree(int ID);
int _get_vertex(int ID);
VERTEX *resize_array(VERTEX *vertex_array,int new_size);
VERTEX *arr = (VERTEX*)calloc(N, sizeof(VERTEX)); // dynamic allocation and initialization to NULL\0
int main(void)
{
int vertex_counter = 0 ;
int starting_size_of_array = sizeof(VERTEX)*N;
}
I get the error : error C2099: initializer is not a constant
我收到错误:错误C2099:初始化程序不是常量
I want the VERTEX array to be global - in order for me to access this array anywhere . so how come it's not constant? N is under #define , and VERTEX has it's declaration in th .h file.
我希望VERTEX数组是全局的 - 以便我可以在任何地方访问这个数组。那怎么来不恒定呢? N在#define下,VERTEX在.h文件中有声明。
2 个解决方案
#1
3
First off, the initialiser isn’t a constant. You need to initialise the global from within a function – e.g. main:
首先,初始化器不是常量。您需要在函数内初始化全局 - 例如主要:
VERTEX *arr;
int main(void)
{
arr = (VERTEX*)calloc(N, sizeof(VERTEX));
}
But you should not use globals in the first place, if avoidable (and it usually is). It destroys your code design.
但是如果可以避免的话,你不应该首先使用全局变量(通常是这样)。它破坏了你的代码设计。
#2
0
The value calloc() will return is not constant. You can init arr to NULL then initialize it during your program start up.
calloc()返回的值不是常量。您可以将init arr设置为NULL,然后在程序启动期间初始化它。
int main(void)
{
int vertex_counter = 0 ;
int starting_size_of_array = sizeof(VERTEX)*N;
}
#define N 100 /