3

Here is the program the array automatically initialize to zero and first element initialize to 1 when declare as int arr[10]={1}

#include<stdio.h>

int main()
{
    int i;
    int arr[10]={1};
    for(i=0;i<10;i++)
    {
        printf("\n%d",arr[i]);
    }
return 0;
}

how array elements are initialized to zero expect the first element?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Anway Kulkarni
  • 261
  • 2
  • 11
  • 5
    It will hep you - http://stackoverflow.com/questions/629017/how-does-array100-0-set-the-entire-array-to-0 – Sathish Aug 18 '15 at 09:51
  • your question is changed? any how following @sourav answer applicable to you – venki Aug 18 '15 at 11:16

1 Answers1

2

The array elements are initialized based on the initialization rule for aggregate type with initialization lists, as specified in C standard.

It mentions, if there are less number of initializers supplied in the brace-enclosed list than that of the number of element in the aggregate type, the remaining elements in the aggregate type will be initialized with the value as if they have static storage duration, i.e., a value of 0.

To quote C11, chapter §6.7.9, Initialization (emphasis mine)

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 regarding the initialization of variables having static storage duration,

[..] If an object that has static or thread storage duration is not initialized explicitly, then:

  • [...]
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • [...]

So, very rightly, in your case

  int arr[10]={1};

arr[0] is having a value 1, arr[1] to arr[9] all are set to 0.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261