It is not duplicate to the above question as statics
differences are not covered and the answers have errors.
This is a basic break-down question about memory organization within a process, and more specifically, default array values.
In a code below:
arr1
is allocated statically in a memory block near machine instructions and at some point default-initialized to 0
arr2
is supposed to be allocated on a stack when function frame is created, it is never default-initialized
arr3
is same as arr1
[?]
arr4
is same as arr2
[?]
arr5
... now my main question besides the above two is how does the static
variable inside a class differs from a static
variable inside a function? I cannot access uninitialized arr5
element. In which cases I can?
int arr1[5];
void func() {
int arr2[5]; printf("%d\n", arr2[0]); // [2]
static int arr3[5]; printf("%d\n", arr3[0]); // [3]
}
class MyClass {
public:
int arr4[5];
static int arr5[5];
};
int main()
{
printf("%d\n", arr1[0]); // [1]
func();
MyClass obj;
printf("%d\n", obj.arr4[0]); // [4]
//printf("%d\n", obj.arr5[0]); // [5]
std::cin.get();
}
Output:
0
-858993460
0
-858993460