Single-Dimension Arrays


What is an Array?

An array is a collection of variables of the same type that are referred to by common names. An array is accessed by a specific element index. In C, all arrays have a fixed memory position. The minimum address corresponds to the first element and the maximum address to the last element. Arrays can have more than one dimension. The most common array is a null-terminated string, which is simply an array of characters closed by a null.


Single-Dimension Arrays

The general form for declaring a single-dimension array is

type variable_name[size];

Like other variables, arrays must be explicitly declared so that the compiler can allocate space in memory for them. Here, type declares the base type of the array, which is the type of each element in the array, and size defines how many elements the array will hold. For example, to declare a 100-element array called numbers of type int, use this statement:

int numbers[100];

An element is accessed in the array name index. This is the name of the array by placing the index of the element in square brackets. For example,

numbers[2] = 10; // 10 is set the array index of 2 position

In C, all arrays have 0 as the index of their first element. Therefore you write -

char a[7];

you are declaring a character array that has seven-element, a[0] through a[6].

Sample Program

Program
#include <stdio.h>

int main() {
  int a[10]; /* this declares a 10-integer array */
  int i;
  
  /* load a with values 0 through 9 */
  for(int i=0; i<10; i++)
  {
   a[i] = i;
  }
  
  /* display contents of a */
  for(int i=0; i<10; i++)
  {
   printf("%d ", a[i]);
  }
  return 0;
}

The amount of storage needed to hold an array is directly related to its type and size. For single dimension arrays, the total size in bytes is calculated as shown here:

total bytes = sizeof(base type) a size of array

There is no limit to examining C's arrays. You can overwrite both ends of an array and write it to any other variable's data or even program code. As a programmer, it is your job to discover what that is and to bring it about. For example, this code will compile without error, but it is incorrect because the array count for the loop will be exceeded:

Sample Program

Program
#include <stdio.h>

int main() {
  int a[10]; /* this declares a 10-integer array */
  int i;
  
  /* this causes count to be overrun */
  for(int i=0; i<100; i++)
  {
   a[i] = i;
  }
  return 0;
}

Single-dimension arrays are essentially lists of information of the same type that are stored in contiguous memory locations in index order. For example, the table shows how array b appears in memory if it starts at memory location 2000 and is declared as shown here:

char d[5];

Element b[0] b[1] b[2] b[3] b[4]
Address 2000 2001 2002 2003 2004