Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

gcc

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.

like image 896
Tom Avatar asked Apr 23 '26 17:04

Tom


2 Answers

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.

like image 108
P.P Avatar answered Apr 25 '26 09:04

P.P


The contents of a variable (and by extension, the elements of an array) that do not have static storage duration (globals, static locals) are undefined.

The fact that the last element in the array happens to be 0 essentially is random.

like image 29
dbush Avatar answered Apr 25 '26 10:04

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!