CSCD-255
2015-02-09


Arrays (Ch. 21)

The declaration int vals[5] = {10, 40, 70, 90, 120}; sets up this part of memory

The vals array

 
10 vals[0]
40 vals[1]
70 vals[2]
90 vals[3]
120 vals[4]

Each cell in the array is a default  int, which for us means four bytes.  The total space occupied by the array is 20 bytes, five occurrences of four bytes.  The total space allocated to the array in bytes is available through the sizeof operator (that is, sizeof vals has the value 20).  The space required for cell vals[0] is sizeof vals[0]sizeof is a unary operator and so has the second highest precedence, just under () and [].

Note that the subscripts (the number in square brackets) range from 0 to 4 (5-1).

Demonstration programs

Declaration of an array of type int, data entry from the keyboard, and then minor manipulation:  sum the contents and show the average.
demo1.txt   demo1.c   demo1.exe

Declaration of several arrays of type int, showing the use of array initializers as shown above for int vals[5].  It also shows what happens if there is a mismatch between the declared array size and the array initializer:  if the initializer is smaller than the array, the rest of the cells are filled with zero.  If the initializer is larger than the array, the compiler generates a warning.  The excess entries are ignored.
demo2.txt   demo2.c   demo2.exe

Note:  if you want to declare an array and initialize the entire array to zero, you just need to set the first.  That cell is expressly set to the number you give and then all other cells are set to zero.

int totals[100] = { 0 };

Declaration of an array of type int, showing the use of array initializers to determine the number of cells actually in the array.
demo3.txt   demo3.c   demo3.exe