C Programming - Declarations and Initializations - Discussion

Discussion Forum : Declarations and Initializations - Find Output of Program (Q.No. 9)
9.
What is the output of the program
#include<stdio.h>
int main()
{
    int a[5] = {2, 3};
    printf("%d, %d, %d\n", a[2], a[3], a[4]);
    return 0;
}
Garbage Values
2, 3, 3
3, 2, 2
0, 0, 0
Answer: Option
Explanation:
When an automatic array is partially initialized, the remaining elements are initialized to 0.
Discussion:
38 comments Page 1 of 4.

Sayeed said:   7 years ago
HERE a[5]=(2,3) means;

a[0]=2 and a[1]=3 then fora[2],a[3],a[4] are not having values that means we are not giving initialization to those values.

So, those values are automatically initialised to zero when we are calling to see the output it will display as 0,0,0.
(4)

Saga jarvis said:   4 years ago
Here the in the array only first to element are initialized (ie. Partially) , so in this;

Case 1: compiler automatically initialize to zero.
Case 2: if none of the are initialized then it would be the garbage values.
Case 3: If all are initialized then it will print as the normal way (ie. How they initialized in that way).
(2)

Saga jarvis said:   4 years ago
Here the in the array only first to element are initialized (ie. Partially) , so in this;

Case 1: compiler automatically initialize to zero.
Case 2: if none of the are initialized then it would be the garbage values.
Case 3: If all are initialized then it will print as the normal way (ie. How they initialized in that way).
(1)

Praj said:   6 years ago
If an array is declared globally then uninitialized index value will be automatically set to zero. If the array is declared internally then it contains garbage value. Right?
(1)

Veer Singh said:   6 years ago
In C if there is partial initialization then all remaining value will be zero by default. if there is no initialization then garbage value will be by default.

int a[5]={2,3} a[2]=0,a[3]=0.....

if int an [5] only then a[0] a[1] will have a garbage value.
(1)

Vasu said:   8 years ago
There is a[5] = {2,3,0,0,0}.
i.e. a[0] = 2.
a[1] = 3.
a[2] = 0.
a[3] = 0.
a[4] = 0.
So, the value of a[2]=0, a[3]=0 & a[4]=0.
(1)

Raja Ravi said:   7 years ago
What is automatic array?

Siva said:   1 decade ago
As per gcc compiler it will take garbage values where non existing elements and existing elements a[0] = 2, a[1] = 3, a[3] = garbage value, a[4] = garbage value.

Sri hari said:   10 years ago
In a array always the numbering of elements start from 0 or 1? We need to consider the starting element as a[0] or a[1].

Priya said:   9 years ago
#include<stdio.h>
int main()
{
int a[3] = {2, 3};
printf("%d, %d,%d\n", a[2], a[3],a[4]);
return 0;
}

Output for above program is like this: [0,-1612,-2697].

Why compiler giving garbage value if it is partially initialized?

Please explain and correct me if I am wrong..!


Post your comments here:

Your comments will be displayed after verification.