I'm using the GCC compiler on Linux. I don't understand how variables work in array sizes.
When I run:
char string[6];
string[0] = 'h';
printf("%s", string);
As expected, it outputs: h
If I run:
int x = 1;
char string[5 + x];
string[0] = 'h';
printf("%s", string);
it outputs h followed by � and other random characters. I guess it's accessing memory addresses, it's not supposed to. The characters are different every time, it's run.
When I do the same but replace line two with "char string[5 + x] = {}" It errors: variable-sized object may not be initialized.
If I do the same with an integer array, it works perfectly fine if I type "int array[5 + x] = {};" but not "int array[5 + x]"
Are variables allowed in the size declarations of int arrays, but not in char arrays/strings?
As noted in comments, your problem is that the below invokes undefined behavior.
The undefined behaviour stems from using
stringas a string. Strings in C require a null terminating character to signal the end of the string. Your variable length array has not been initialized (apart from the first character) so the contents are indeterminate. You have a5 + xsized chunk of memory, but that memory could be in any state.In the first case,
string[1]was clearly0, thus null-terminating the string. This is not guaranteed as you can see from the second example whereprintfprinted gibberish because it didn't see the next character after'h'being a null terminator.With a static-sized array we would initialize it with
{0}or{}to set the contents to zero, but VLAs may not be initialized this way.