#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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With