8

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.

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In C you shouldn't really cast the result of malloc - you only really need to do that in C++ - it should be avoided in C as it can mask otherwise helpful warnings.
If you want to be general, use sizeof (*str), so you don't have to repeat the type name. Furthermore, in C you should not cast the result of malloc.
3

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));
    ...
}

2 Comments

sizeof (char) is 1 by definition. If you want to write code that works with any type, use sizeof (*str).
@Ben: true, but it's a good habit to include the sizeof regardless of the type. I'm well aware of the arguments in favour of sizeof(*str) but I still prefer sizeof(char) in this instance.
1
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

2 Comments

If you want to be general, use sizeof (*str), so you don't have to repeat the type name. Furthermore, in C you should not cast the result of malloc.
In C you shouldn't really cast the result of malloc - you only really need to do that in C++ - it should be avoided in C as it can mask otherwise helpful warnings.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.