Suddenly think of a few days ago the classmate asked me why not initialized the value of the array is random, found that the confusion itself is also present, so I summarize the experience.
1. First, not all uninitialized arrays have values that are random. For arrays that are not initialized, there are two kinds of cases:
(1) Global array, which is the array defined outside the main function, the default value of the element is all 0
(2) A local array, defined in an array inside the function, whose value is random by default.
#include <stdio.h>#defineLENGTH 5intA[length];intMain () { for(intI=0; i<length;i++) {printf ("%d", A[i]); } printf ("\ n"); intB[length]; for(intI=0; i<length;i++) {printf ("%d", B[i]); }}
0 0 0 0 0 4200814 4200720 the 8 A 0 (0x0) 0.739continue.
From the code results it is clear that the default values for the global array and the local array are different.
2. Let's talk about why the local array is random. The local array is placed on the stack, and the global array is placed in the static area.
Because the local array is placed on the stack, the stack operation is in the stack and out of the stack. We declare an array, in fact, just move the stack top pointer. The data in the stack is the data that was left over from the previous stack. The stack is not emptied. So the data is random.
#include <stdio.h>voidtest ();intMain () {test (); Test ();}voidTest () {inta[5]; for(intI=0;i<5; i++) {printf ("%d", A[i]); } printf ("\ n"); for(intI=0;i<5; i++) {A[i]=i; } for(intI=0;i<5; i++) {printf ("%d", A[i]); } printf ("\ n");}
// output 1944480941 4200720 Span style= "color: #800080;" >6356884 4200814 0 1 2 3 4 0 2 3 4 0 2 3 4
When we call a function two times in a row. We find that only the first value seems to be random. Because we have two times the same operation on the stack's address operation is also the same. The first time the function changes the stack is not emptied by the stack, so the second random value is the first time the last data.
The value of the uninitialized array of the C language is what is random