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 h开发者_开发技巧ere, any help would be greatly appreciated.
The way to do it is with malloc
. First declare just a pointer:
char *str;
Then in the init function you malloc
it:
str = malloc(sizeof(*str) * size_of_array);
This allocates size_of_array
elements of the size that str
points to (char
in this case).
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. 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.
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.
Don't forget to deallocate the memory using free
Create a 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.
精彩评论