0
#include <stdio.h>

int main()
{
    int a[5]={1} ;
    int b[5];
    b[0]=1 ;
    printf("\na[0]=%d, a[1]=%d, a[2]=%d, a[3]=%d, a[4]=%d",a[0],a[1],a[2],a[3],a[4]);
    printf("\nb[0]=%d, b[1]=%d, b[2]=%d, b[3]=%d, b[4]=%d",b[0],b[1],b[2],b[3],b[4]);

    return 0 ;
}

Look at the code. I have assigned two integer array partially (1 element is assigned out of 5) in two procedure.

1st one is assigned at once with braces.

2nd one is assigned by accessing one array index.

And then I am printing the whole array.

In 1st array I am getting 0 (zero) in unassigned index. And in 2nd array I am getting garbage value in unassigned index.

May you please explain.

Please don't explain what is happening here. But kindly explain why it is happening? The reason.

ANUPAM
  • 53
  • 2
  • 3
  • 11
  • No, there somebody asked how to assign sam element. But here the question is. If I dont assign the full array in several ways. Why the values are being differing. The reason. :) – ANUPAM Nov 12 '17 at 15:00

2 Answers2

1

With

int a[5]={1} ;

you initialize the first element to 1 and the rest will automatically be initialized to 0.

With

int b[5];
b[0]=1 ;

you don't initialize any of the elements, the contents of the array (after definition) will be indeterminate. Then you assign the value 1 to b[0], leaving the rest of the array uninitialized.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

It's correct behavior.

int a[5]={1} ; // 1,0,0,0,0

the array is initialized with these values.

For the second case only b[0] is initialized. Rest of the elements contains indeterminate values.

An example from standard itself 6.7.9.27 [N1570]

EXAMPLE 4 The declaration

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

initializes the first column of z as specified and initializes the rest with zeros.

In teh same passage in standard it says 6.7.9.21

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

And the rule for that standard mentions:- 6.7.9.10

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
  • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
user2736738
  • 30,591
  • 5
  • 42
  • 56