Using Arrays in C

This first section is the equivalent of our introductory page on Pascal arrays.

An array is a data structure used to store data items of the same type. In the example below an array is used to store the monthly rainfall of a location in a single year:

int rainfall[12];

Array declarations show the identifier (in this case rainfall), the number of elements and the type (int). To identify individual members of the array, the index (also known as subscript) is given in square brackets. In C the arrays are zero-based, meaning that first element's index is zero. The statement rainfall[1] = 30; uses the index 1 to assign the value 30 to the second integer in the array (representing February).

This array is used to input monthly rainfall in the following program.

#include <stdio.h>

int main()
{
  int rainfall[12];
  int count;
  int total = 0;
  for (count = 0; count < 12; count++)
  {
    printf("Please enter the rainfall for month %d: ", count + 1);
    scanf("%d", &rainfall[count]);
  }
    printf("rainfall stored\n");
    for (count = 0; count < 12; count++)
  {
    printf("month %d: %d\n", count + 1, rainfall[count]);
    total += rainfall[count];
  }
  printf("Total for year: %d", total);
  return 0;
}
    

Initialising an array

Whereas Pascal uses round brackets and Smart Pascal uses square brackets, you must enclose the initial values of an array in braces in C. An example of the syntax is:

int my_ints[3] = {3, 5, 10};

It is convenient to initialise an array of char together with the declaration e.g.

char surname[20] = "Morrison";.
This is less tedious than the alternative:
char surname[20] = {'M', 'o', 'r', 'r', 'i', 's', 'o', 'n'};

If you try

char surname[20];
surname = "Morrison";
you will receive an error message such as
incompatible types when assigning to type 'char[20]' from type 'char *'

Instead, use strcpy(surname, "Morrison");

Initialise a two-dimensional array with nested, comma-separated braces e.g.

int my_ints[2][3] = {{3, 5, 10}, {3000, 5000, 10000}};

Passing an Array to a Routine

When you pass an array to a routine you are passing by reference, achieving the same result as a var parameter in Pascal. This means that when you change the value of an array element within the routine it will be changed in the original array that is passed. A simple example follows.

#include <stdio.h>

void hundredth(int ints[], int array_size)
{
  int i;
  for (i = 0; i < array_size; i++)
  {
    ints[i] /= 100;
  }
}

int main()
{
  int my_ints[8] = {100, 200, 400, 800, 1500, 3000, 5000, 10000};
  hundredth(my_ints, 8);
  int i;
  for (i = 0; i < 8; i++)
  {
    printf("%d ", my_ints[i]);
  }
  return 0;
}
    

Output:

1 2 4 8 15 30 50 100
Programming - a skill for life!

How to apply your knowledge of Pascal when learning C/C++