0
#include <stdio.h>

int main()
{
    int a[100];
    int b[100] = {0};
    int c[100] = {1, 200};

    printf("%d %d %d\n", a[0], a[50], a[99]);
    printf("%d %d %d\n", b[0], b[50], b[99]);
    printf("%d %d %d\n", c[0], c[1], c[99]);

    return 0;
}

Output:

[vnathan.VNATHAN-L430] ➤ ./a.exe

1629978992 1767859565

0 0 0

1 200 0


If none of the array elements were initialized then we have some junk value (a[]) where as if we declare one element (b[]) or first few elements (c[]) then remaining elements in the array were assigned to 0. Why is it so? I expect uninitialized elements to have junk value as array a[].

Viswesn
  • 4,674
  • 2
  • 28
  • 45
  • 2
    That's just the rules of C. Initialize one, initialize all. (Although there is an exception for initializing a char array from a string literal). – M.M Aug 03 '14 at 09:04
  • btw static local variables are initialized to zeros, even if no explicit initialization is done – mangusta Aug 03 '14 at 09:07

2 Answers2

3

According to the С Standard

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

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;

So for this definition

int b[100] = {0};

the first element is initialized explicitly by 0 and all other elements are initialized implicitly the same way as objects with the static storage duration that is with zeroes.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

That is the concept of C language.

But there is a concept called designated initialization.

This will be useful for your for further understanding. https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html

mahendiran.b
  • 1,315
  • 7
  • 13