Arrays - An Introduction

Array is a data-structure that can store a fixed sized collection of similar type of elements. Array is also referred as vector in some programming languages. To understand specific implementation of arrays in language C, you may want to refer to my notes from book - The C programming language - by Dennis Ritchie and Brian Kernighan

When to use arrays

Consider a situation where you want to declare variables to hold number of days in all the months. We can have 12 variables like - days_jan, days_feb, days_march and so on. Alternatively, we can declare an array such as:

int days_months[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
The above array declaration reserves a contiguous memory space for 12 elements of type int. Along with the declaration of the variable, we also initialized the array to contain the values of the days of a particular month. For example, to access the days in month of march - we can refer to the array as:

days_months[2]
To access individual array elements, we need to use the above syntax to specify the appropriate index. In most of the programming languages, the array indexing starts from 0. Which means, to access the days in month of March, we need to access the 3rd element in the given array. And to access the third array element, the index will be 2 (and not 3) since the first element is at index 0.

Multi Dimensional arrays

Arrays are not only limited to single dimension. We can have any number of dimensions. Let us see an example where in we have a 2-dimensional array which is used to store the state of a tic-tac-toe game. To store the state of tic-tac-toe game we need to have a 2-dimensional array with 3 rows where each rows contains 3 columns - which actually resembles the game very closely:

#include <stdio.h>
#define EMPTY_VALUE ' '
#define CROSS_VALUE 'X'
#define NOUGHTS_VALUE '0'

int main()
{
    int row;
    int col;

    int game[3][3];

    // Initialize the state to empty
    for (row = 0; row < 3; row++)  {
        for (col = 0; col < 3; col++) {
            game[row][col] = EMPTY_VALUE;
        }
    }

    // Print the current state
    for (row = 0; row < 3; row++)  {
        for (col = 0; col < 3; col++) {
            printf("%c ", game[row][col]);
        }
        printf("\n");
    }
}
The above program may return output as:
X 0 0
0 X 0
X 0 X

You can always pass an array to a function or return an address of array from a function. Array address can be easily extracted by accessing the address of the first element - &array[0]. In fact, you can simply refer to the array by its name to get the base address and assign it to corresponding pointer:

char *ptr;
char str_array[10];
ptr = str_array;

As a concluding remark I would like to mention that arrays and pointers are very tightly coupled to each other. Refer to this article to understand more about this relation.