简体   繁体   English

C:定义用户可以声明其大小的全局数组变量

[英]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). 我想用C语言设置一个int数组的全局引用,但我想在main函数中初始化它(实际上用户将声明它的大小)。 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. 将指向int的指针声明为全局变量,并使用malloc在main中初始化它。

/* 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). 或者,优选地,声明它们extern在包括在使用所述阵列,包括在那里它们被定义的源任何源文件头文件(以确保类型一致性)。

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

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