简体   繁体   English

C - 在函数中初始化全局数组

[英]C - Initializing a global array in a function

I have an array that i want to make global, and i want to initialize in a function call. 我有一个我想要创建全局的数组,我想在函数调用中初始化。 I want to first declare it without knowing it's size: 我想首先声明它而不知道它的大小:

char str[];

and later initialize it: 然后初始化它:

str = char[size];

How can i do this? 我怎样才能做到这一点? I'm very new to c and perhaps I'm going completely the wrong way here, any help would be greatly appreciated. 我对c很新,也许我在这里完全走错路,任何帮助都会非常感激。

The way to do it is with malloc . 这样做的方法是使用malloc First declare just a pointer: 首先声明一个指针:

char *str;

Then in the init function you malloc it: 然后在init函数中你将它malloc

str = malloc(sizeof(*str) * size_of_array);

This allocates size_of_array elements of the size that str points to ( char in this case). 这将分配str指向的大小的size_of_array元素(在本例中为char )。

You should check if the allocation failed: 您应该检查分配是否失败:

if (str == NULL) {
    // allocation failed
    // handle the error
}

Normally you have to make sure you free this allocated memory when you're done with it. 通常情况下,你必须确保在完成后free这个已分配的内存。 However, in this case str is global, so it never goes out of scope, and the memory will be free d when the program ends. 但是,在这种情况下, str是全局的,所以它永远不会超出范围,并且当程序结束时内存将是free

Make your global array declaration look like this: 使您的全局数组声明如下所示:

char *str = NULL;

Then in your initialisation function do something like this: 然后在初始化函数中执行以下操作:

void init(int size)
{
    ...
    str = malloc(size * sizeof(char));
    ...
}
char* str;

str = (char*)malloc(size*sizeof(char));

You can skip the *sizeof(char) since sizeof(char) == 1 by definition. 您可以跳过*sizeof(char)因为sizeof(char) == 1的定义。

Don't forget to deallocate the memory using free 不要忘记使用free释放内存

Create a char* str; 创建一个char* str; instead of an array. 而不是数组。 Then, allocate the required amount of memory using malloc or calloc and do the initialization in the function call itself. 然后,使用malloc或calloc分配所需的内存量,并在函数调用本身中进行初始化。

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

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