Node:Initializing arrays, Next:, Previous:Arrays and nested loops, Up:Arrays



Initializing arrays

As mentioned above, you must initialize your arrays or they will contain garbage. There are two main ways to do so. The first is by assigning values to array elements individually, either as shown in the example below, or with for loops. (See Arrays and for loops, above.)

my_array[0] = 42;
my_array[1] = 52;
my_array[2] = 23;
my_array[3] = 100;
...

The second method is more efficient and less tedious. It uses a single assignment operator (=) and a few curly brackets ({...}).

Recall that arrays are stored by row, with the last index varying fastest. A 3 by 3 array could be initialized in the following way:

int my_array[3][3] =
{
  {10, 23, 42},
  {1, 654, 0},
  {40652, 22, 0}
};

Here is a small program that uses the above initialization:

#include <stdio.h>

int main()
{
  int row, column;

  int my_array[3][3] =
  {
    {10, 23, 42},
    {1, 654, 0},
    {40652, 22, 0}
  };

  for (row = 0; row <=2; row++)
    {
      for (column = 0; column <= 2; column++)
	{
	  printf("%d\t", my_array[row][column]);
	}
      printf("\n");
    }

  printf("\n");

  return 0;
}

The internal curly brackets are unnecessary, but they help to distinguish the rows of the array. The following code has the same effect as the first example:

int my_array[3][3] =
{
  10, 23, 42,
  1, 654, 0,
  40652, 22, 0
};

The same array initialization could even be written this way:

int my_array[3][3] =
  {10, 23, 42, 1, 654, 0, 40652, 22, 0};

Using any of these three array initializations, the program above will print the following text:

10      23      42
1       654     0
40652   22      0

Note 1: Be careful to place commas after every array element except the last one before a closing curly bracket (}). Be sure you also place a semicolon after the final curly bracket of an array initializer, since here curly brackets are not delimiting a code block.

Note 2: All the expressions in an array initializer must be constants, not variables; that is, values such as 235 and 'q' are acceptable, depending on the type of the array, but expressions such as the integer variable my_int are not.

Note 3: If there are not enough expressions in the array initializer to fill the array, the remaining elements will be set to 0 if the array is static, but will be filled with garbage otherwise.