Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is every value not initialized to 0? [duplicate]

#include <stdio.h>

int main(void) {
    int memo[1000];
    for (int i = 0; i < 1000; i++) {
        printf("%d\t", memo[i]);
    }
    return 0;
}

I thought everything should be initialized to 0 but it is not. Is there any reason for this? Thank you so much for your help.

like image 954
Kang Avatar asked Jan 24 '23 09:01

Kang


1 Answers

Objects defined locally with automatic storage in a function body are uninitialized in C. The values can be anything, including trap values on some architectures that would cause undefined behavior just by reading them.

You can initialize this array as int memo[1000] = { 0 };. The first element is explicitly initialized to 0, and all the remaining ones will also initialized to 0 because any element for which the initializer is missing will be set to 0.

For completeness, int memo[1000] = { 42 }; will have its first element set to 42 and all remaining ones to 0. Similarly, the C99 initializer int memo[1000] = { [42] = 1 }; will have its 43rd element set to 1 and all others set to 0.

like image 73
chqrlie Avatar answered Jan 26 '23 23:01

chqrlie