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.
The arrays can be declared and initialized globally as well as locally(i.e., in the particular scope of the program) in the program.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With