Home > OS >  Difference in array initialization in C
Difference in array initialization in C

Time:12-04

I have this code:

#include <stdio.h> 
int main()
{
    int arr2[5];
    arr2[0] = 0;
    arr2[1] = 1;
    arr2[2] = 2;
    arr2[3] = 3;
    int arr3[5] = {1, 2, 3, 4};
}

And when I'm printing the fifth position of each array I'm getting different results:

printf("Fifth: %d\n", arr2[4]); // Prints Random number 
printf("Fifth: %d\n", arr3[4]); // Prints Zero!

output:

Fifth: -858993460
Fifth: 0

I understand that the first is a pointer to the location of the fifth in the memory, and the second one is just how the array was initialized with 0. I don't understand why they give me 2 different values. I have set the size of the array to 5 in both cases; why is this happening?

CodePudding user response:

With

int arr2[5];
arr2[0] = 0;
arr2[1] = 1;
arr2[2] = 2;
arr2[3] = 3;

you don't actually initialize the array. You create it uninitialized and with indeterminate values for each element. Then you assign to four separate elements, leaving the fifth uninitialized.

On the other hand, with

int arr3[5] = {1, 2, 3, 4};

you explicitly initialize all elements. The first four with explicit values, and then the remaining (single, for this specific array) elements with zero.

CodePudding user response:

A local variable which isn't initialized explicitly gets indeterminate values, "garbage" if you will. Printing an indeterminate value is unspecified behavior, meaning that the output may not follow any logic at all. You might even get different values each time your print the same uninitialized location.

In some cases, accessing an uninitialized local variable is even undefined behavior - see (Why) is using an uninitialized variable undefined behavior?

Initialization in C happens at the same line as variable declaration. Since there is no = on the line int arr2[5];, there is no initialization taking place. The following lines below that one is not initialization, but assignment in run-time. And you left out the final item, so it remains indeterminate.

However, in case an array is partially initialized, the rest of the items in the array get implicitly initialized "as if they had static storage duration", which in practice means that they get set to zero and that behavior is well-defined.

CodePudding user response:

Your data is on the stack. For such variables the standard does not guarantee an initial value (so it is undefined). You did not initialize arr2[4], and you are getting a value for which the standard does not provide any guarantee, so they could be literally anything.

  • Related