Tom Tom - 1 month ago 14
C Question

Does C always initialize the last element in char array to zero?

By running this code

char array[6];
int i;
for ( i = 0; i < 6; ++i )
printf("%i ", array[i]);


Possible output:

64 0 -64 77 67 0


I get always the last element 0, although I was expecting random value. It is compiler dependent? I'm using gcc.

usr usr
Answer

No. There's no such thing guaranteed by the C standard for local variables.

The values of the uninitialized array has indeterminate values. So, you can't access them and since you do, your code has undefined behaviour.

But the variables with static storage duration such as global variables, static qualified variables etc are initialized with zero.