Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 993
Daniel Avatar asked Nov 21 '10 21:11

Daniel


People also ask

Can we initialize array globally?

The arrays can be declared and initialized globally as well as locally(i.e., in the particular scope of the program) in the program.


1 Answers

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 freed when the program ends.

like image 193
Nathan Fellman Avatar answered Sep 19 '22 04:09

Nathan Fellman