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 way to do it is with
malloc. First declare just a pointer:Then in the init function you
mallocit:This allocates
size_of_arrayelements of the size thatstrpoints to (charin this case).You should check if the allocation failed:
Normally you have to make sure you
freethis allocated memory when you’re done with it. However, in this casestris global, so it never goes out of scope, and the memory will befreed when the program ends.