C Arrays Tutorial

In this C tutorial we learn about complex data containers, called arrays.

We cover how to declare and initialize an array, and access and assign data with the indexer and loops.

We also cover multi-dimensional arrays that allows for a relational database array structure.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is an array

An array is a collection of similar data type items. Think of an array as a single table row where each element has its own cell.

As an example, let’s consider a string of characters like the word “Hello”. Each letter of the word would be contained in its own cell of a row.

Hello

Each cell also has a numerical index that corresponds to the value.

01234
Hello

If we need to access the element in a specific cell, we use the index number for that cell.

An array can only store elements of the same data type. For example, if we create an array of ints, we can’t store floating point numbers inside of it.

How to declare an array

To declare an array we specify it’s type and name, immediately followed by open and close square brackets.

Between the square brackets we specify the amount of elements the array can hold.

Syntax:
 type name[size];
Example:
#include <stdio.h>

int main()
{
    int numbers[10];

    return 0;
}

In the example above we declare an array of integers, called numbers, that will be able to hold 10 elements.

When an array has been declared, we cannot change its size or type at runtime.

How to initialize an array

We can assign values directly to an array when we declare it, called initialization.

To initialize an array of values, we use the assignment operator and specify our values, separated by a comma, between open and close curly braces.

Syntax:
 type name[size] = { value1, value2, ... };

When we declare an array, we have to specify the array size, but when we initialize an array we can omit the size.

The compiler will automatically use the amount of values we assign as the size of the array.

Example:
#include <stdio.h>

int main()
{
    int numbers[] = { 30, 2, 487, 11, 14 };

    return 0;
}

In the example above, we assign 5 values to the array so the compiler will automatically create an array with a size of 5.

How to access elements inside an array

As previously mentioned, an array is created with a set of numerical indices that correspond to its values.

01234
Hello

To access an array element, we specify the index of the element we want to access between square brackets.

Syntax:
 arrayName[index];
Example:
#include <stdio.h>

int main()
{
    int numbers[] = { 30, 2, 487, 11, 14 };

    printf("%d\n", numbers[3]);

    return 0;
}

In the example above, we access the fourth element in the array at index number 3. When we run the program it prints the number 11 from our array.

An array with a numerical index will always start at 0 and not at 1. So, if we refer to element number 3, the compiler will access the fourth element in our array.

How to assign a new value to an element inside an array

Array element values are mutable, which means they can be changed at runtime.

To change the value of an element, we assign a new value to the index number of the element we want to change.

Syntax:
 arrayName[index] = newValue;
Example:
#include <stdio.h>

int main()
{
    int numbers[] = { 30, 2, 487, 11, 14 };

    printf("Original value: %d\n", numbers[3]);

    numbers[3] = 84657;

    printf("New value: %d\n", numbers[3]);

    return 0;
}

In the example above, we change the value of the fourth element (index 3) to a new value.

How to access array elements with a loop

We can use a loop to iterate through the elements of an array.

To loop through the elements of an array we need to know the amount of elements inside the array.

To determine the number of elements in the array, we divide the total size of the array by the size of the first array element.

Example:
#include <stdio.h>

int main()
{
    int num[] = { 30, 2, 487, 11, 14 };

    size_t s = sizeof(num) / sizeof(num[0]);

    printf("Size of array (s): %d\n\n", s);

    return 0;
}

In the example above, we store the size of the array in a variable of type size_t.

The size_t type is used to represent the size of an object in bytes, therefore we use it as the storage type for the sizeof operator.

Now that we found the size for our array, we can use a simple for loop to iterate through the elements.

Example:
#include <stdio.h>

int main()
{
    int num[] = { 30, 2, 487, 11, 14 };

    // find the array size
    size_t s = sizeof(num) / sizeof(num[0]);
    printf("Size of array (s): %d\n\n", s);

    // iterate through elements
    for (int i = 0; i < s; ++i)
    {
        printf("Element: %d, value: %d\n", i, num[i]);
    }

    return 0;
}

Multi-dimensional array

A multi-dimensional array is similar to a relational database structure. In a simple array we have a single row of elements, in a multi-dimensional array we have both rows and columns.

The rows are represented by the first index, and the columns are represented by the second index.

 col 1col 2col 3
row 1x[0][0]x[0][1]x[0][2]
row 2x[1][0]x[1][1]x[1][2]
row3x[2][0]x[2][1]x[2][2]

A multi-dimensional array is also known as a 2D array.

How to initialize a multi-dimensional array

To declare a multi-dimensional array we use a second set of square brackets after its name.

It’s important to note that we have to specify the dimension sizes or the compiler will raise errors.

Syntax:
 type name[rowSize][colSize];
Example:
#include <stdio.h>

int main()
{
    int num[4][3];

    return 0;
}

The example above declares a multi-dimensional array with 4 rows and 3 columns.

To initialize a multi-dimensional array, we declare the array like we did above but add an assignment operator and a code block.

Inside the code block, we specify a set of comma separated values for each row of the array. Each row is wrapped in its own set of curly braces, and multiple rows are separated by a comma.

Syntax:
type name[rowSize][rowSize] =
{
	{ val1, val2, ... }, // row set 1
	{ val1, val2, ... }  // row set 2
};

The row set is in the first dimension, and each value in a row set represents a column in the second dimension.

Example:
#include <stdio.h>

int main()
{
    int num[4][3] =
    {
        { 10, 11, 12 },
        { 20, 21, 22 },
        { 30, 31, 32 },
        { 40, 41, 42 }
    };

    return 0;
}

In the example above, we declare a multi-dimensional array with 4 rows and 3 columns.

We can visualize the example above in a table of 4 rows and 3 columns.

 colcolcol
row101112
row202122
row303132
row404142
How to access multi-dimensional array elements

To access a single element in a multi-dimensional array, we use the indices of the value we want between the two sets of square brackets.

As mentioned before, the first set of square brackets refer to the row, and the second set of square brackets refer to the column.

Example:
#include <stdio.h>

int main()
{
    int num[4][3] =
    {
        { 10, 11, 12 },
        { 20, 21, 22 },
        { 30, 31, 32 },
        { 40, 41, 42 }
    };

    printf("%d\n", num[2][1]);

    return 0;
}

In the example above, we access the value at row number 2 (third row) and column number 1 (second column).

How to access multi-dimensional array elements

Because a multi-dimensional array has an extra dimension, we need to use a nested loop.

The outer loop will go into the first row. Then, the inner loop will loop over the elements in that row. Finally, the compiler goes back to the outer loop and continues on to the next row.

Syntax:
// this outer loop iterates over
// the rows (first dimension)
for (int i = 0; i < d1Size; ++i)
{

	// this inner loop iterates over
	// each value (column) in the row
	// (the second dimension)
	for (int j = 0; i < d2Size; ++j)
	{

		// arrayName[i][j];

	}
}
Example:
#include <stdio.h>

int main()
{
    int num[4][3] =
    {
        { 10, 11, 12 },
        { 20, 21, 22 },
        { 30, 31, 32 },
        { 40, 41, 42 }
    };

    // iterate through elements
    for (int i = 0; i < 4; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            printf("num[%d][%d]: %d\n", i, j, num[i][j]);
        }
    }

    return 0;
}

Let’s break down the example above step by step.

  1. The outer loop goes through the rows of the array. This is the first dimension, num[4].
  2. Each time it gets to a row, it goes inside of it, and iterates through all of the columns of that row. This is the second dimension, num[][3].
  3. The outer loop repeats this process for each row in the array.

The print statement prints the row and column numbers i and j, followed by the actual value of that element, num[i][j].

How to pass an array to a function through its parameters

We can pass an array to a function by declaring a function parameter as an array.

Syntax:
type name(arrayType arrayName[])
{
	// function body
}
Example:
#include <stdio.h>

void printIntArray(int arr[], int arrSize);

int main()
{
    int num[] = { 10, 20, 30, 40, 50 };

    printIntArray(num, 5);

    return 0;
}

void printIntArray(int arr[], int arrSize)
{
    for (int i = 0; i < arrSize; ++i)
    {
        printf("array[%d]: %d\n", i, arr[i]);
    }
}

To keep the example above simple, we added a size parameter for the loop inside the function. In a production environment we would check the size dynamically.

Summary: Points to remember

  • An array can only hold values of the same type. We cannot store mixed types in an array.
  • We initialize an array by specifying the values we want inside in the array’s code block.
  • An array’s values are accessed or assigned with the indexer, whether we’re working on single values or in a loop.
  • A multi-dimensional, or 2d, array allows an array to have the same rows and columns structure as a relational database.
  • To access elements in the second dimension of a multi-dimensional loop, we use a nested loop.
  • To pass an array to a function we declare it in the parameter list.