1

If I define an array without initializing all of the values, like so:

int x[10] = {1, 3, 5, 2, 9, 8, 4, 7, 6};

what happens if, for example, I reference x[9]? What value is it fetching? Is it 0 because I haven't defined that value?

Chris Beck
  • 15,614
  • 4
  • 51
  • 87
mttrns
  • 75
  • 6
  • Title answer: When code references an **undefined** element of an array, it is undefined behavior. Post body answer: OTOH, OP example is a reference to a **defined** array element, and `x[9]` is 0. – chux - Reinstate Monica Dec 18 '15 at 20:34

2 Answers2

2

what happens if, for example, I reference x[9]?

It will be zero (as you found out). When you initialize one or more elements of an array, the rest of elements of the array are implicitly initialized to zero.

This is not because you haven't "defined" any value but the behaviour C standard mandates.

C11 draft, §6.7.9, Initialization

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.

That means the x[9] will initialized to 0 as you have explicitly initialized the index range 0-8.

Similarly, if you have:

int i;
int j;

int *ptrs[10] = {&i, &j}; // an array of 10 pointers

The rest of the pointers, index range from 2-9 will be implicitly initialized to null pointers.

P.P
  • 117,907
  • 20
  • 175
  • 238
1

Initializer list will initialize array elements in increasing order of their index. If the size of initializer list is smaller than that of the size of the array then rest of the elements are initialized with 0,

haccks
  • 104,019
  • 25
  • 176
  • 264
  • In java,an `arrayindexoutofbounds` exception will be thrown!!...Is there any similar exception in c?? – Mathews Mathai Dec 18 '15 at 18:11
  • 2
    There are no exceptions in C. Exceptions are constructs for higher level languages. (java, C++, etc) – ForeverStudent Dec 18 '15 at 18:12
  • 1
    @IIIIIIIIIIIIIIIIIIIIIIII ha pointed there is not exception handler in C unlike Java. – haccks Dec 18 '15 at 18:13
  • 2
    @MathewsMathai no it won't - the array has space for 10 members, so accessing `[9]` wouldn't throw an exception - you might (I haven't checked) get a compile-time error that the number of elements in the initalizer doesn't match the size of the array. – Alnitak Dec 18 '15 at 18:16
  • 1
    To be clear, in the general case, the elements are zero-ed in memory (so each byte is zero). – Noldorin Dec 18 '15 at 18:19
  • Okay.Thanks a lot guys!!..I learnt something new about c today!! – Mathews Mathai Dec 18 '15 at 18:27