简体   繁体   中英

C: Define global array variable that user can declare its size

I want to set a global reference of an int array, in C language, but I want to initialize it inside main function (actually the user is going to declare its size). Anyone knows how is this done?

Thanks in advance!

Declare a pointer to an int as a global variable and initialize it in main using malloc.

/* outside any function, so it's a global variable: */
int *array;
size_t array_size;

/* inside main(): */
array_size = user_defined_size;
array = malloc( sizeof(int)*array_size);
if ( array == NULL) {
    /* exit - memory allocation failed. */
}
/* do stuff with array */
free(array);

If you need to access the global variable from another module (source file), declare it there again using

extern int *array;
extern size_t array_size;

or, preferably, declare them extern in a header file included in any source file that uses the array, including the source where they are defined (to ensure type consistency).

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