user1386966
user1386966

Reputation: 3392

how to make a pointer to array of structs global

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

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.

Upvotes: 0

Views: 193

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545608

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 = calloc(N, sizeof *arr);
}

But you should not use globals in the first place, if avoidable (and it usually is). It destroys your code design.

Upvotes: 3

Unknown1987
Unknown1987

Reputation: 1701

The value calloc() will return is not constant. You can init arr to NULL then initialize it during your program start up.

Upvotes: 0

Related Questions