Arrays in C – Declare, initialize and access

Array is a data structure that hold finite sequential collection of homogeneous data.

To make it simple let’s break the words.

  • Array is a collection – Array is a container that can hold a collection of data.
  • Array is finite – The collection of data in array is always finite, which is determined prior to its use.
  • Array is sequential – Array stores collection of data sequentially in memory.
  • Array contains homogeneous data – The collection of data in array must share a same data type.

We can divide arrays in two categories.

  1. One-dimensional array (Or single-dimensional array)
  2. Multi-dimensional array

Why we need arrays?

Let us understand the significance of arrays through an example.

Suppose, I asked you to write a program to input 1000 students marks from user. Finally print average of their marks.

To solve the problem you will declare 1000 integer variable to input marks. Call I/O functions to input marks in 1000 variables and finally find the average.

Think for a while how tedious will be to code if solved using above approach. Declare 1000 variables, take input in all variables, then find average and finally print its average. The above increases length of code, complexity and degrades performance. If you don’t believe, try to code solution using above approach.

To solve above problem efficiently we use arrays. Arrays are good at handling collection of data (collection of 1000 student marks). Mind that in programming, we will always use some data structure (array in our case) to handle a collection of data efficiently.

How to use arrays?

Array representation in memory
Array and variable representation in memory(RAM).

Array in memory is stored as a continuous sequence of bytes. Like variables we give name to an array. However unlike variables, arrays are multi-valued they contain multiple values. Hence you cannot access specific array element directly.

For example, you can write sum = 432; to access sum. But, you cannot access specific array element directly by using array variable name. You cannot write marks to access 4th student marks.

In array, we use an integer value called index to refer at any element of array. Array index starts from 0 and goes till N - 1 (where N is size of the array). In above case array index ranges from 0 to 4.

To access individual array element we use array variable name with index enclosed within square brackets [ and ]. To access first element of marks array, we use marks[0]. Similarly to access third element we use marks[2].

How to declare an array?

Syntax to declare an array.

data_type array_name[SIZE];

Example to declare an array

int marks[5];

How to initialize an array?

There are two ways to initialize an array.

  1. Static array initialization – Initializes all elements of array during its declaration.
  2. Dynamic array initialization – The declared array is initialized some time later during execution of program.

Static initialization of array

We define value of all array elements within a pair of curly braces { and } during its declaration. Values are separated using comma , and must be of same type.

Example of static array initialization

int marks[5] = {90, 86, 89, 76, 91};

Note: Size of array is optional when declaring and initializing array at once. The C compiler automatically determines array size using number of array elements. Hence, you can write above array initialization as.

int marks[] = {90, 86, 89, 76, 91};

Dynamic initialization of array

You can assign values to an array element dynamically during execution of program. First declare array with a fixed size. Then use the following syntax to assign values to an element dynamically.

array_name[index] = some_value;

Example to initialize an array dynamically

marks[0] = 90; // Assigns 90 to first element of marks array
marks[1] = 86; // Assigns 86 to second element of marks array
...
...
...
marks[4] = 91; // Assigns 91 to fifth element of marks array

Instead of hard-coding marks values, you can ask user to input values to array using scanf() function.

scanf("%d", &marks[0]); // Input an integer from user and assigns to first element of marks

scanf("%d", &marks[4]); // Input an integer from user and assigns to fifth element of marks

The array index is an integer value, so instead of hard-coding you can wrap array input code inside a loop.

int index;

// Run a loop from 0 to 4
for(index = 0; index < 5; index++)
{
    // Replace the hard-coded index with 'index' variable
    scanf("%d", &marks[index]);
}

The above code will run 5 times from 0 to 4. In each iteration it ask user to input an integer and stores it in successive elements of marks array.

Example program to implement one-dimensional array

Let us write a C program to declare an array capable of storing 10 student marks. Input marks of all 10 students and find their average.

/**
 * C program to find average of marks using array
 */

#include <stdio.h>

#define SIZE 10 // Size of the array

int main()
{
    int marks[SIZE]; // Declare an array of size 10
    int index, sum;
    float avg;

    printf("Enter marks of %d students: ", SIZE);

    /* Input marks of all students in marks array */
    for(index=0; index<SIZE; index++)
    {
        scanf("%d", &marks[index]);
    }

    /* Find sum of all marks */
    sum = 0;
    for(index=0; index<SIZE; index++)
    {
        sum = sum + marks[index];
    }

    /* Calculate average of marks*/
    avg = (float) sum / SIZE;

    /* Print the average marks */
    printf("Average marks = %f", avg);

    return 0;
}

Output –

Enter marks of 10 students: 90 86 89 76 91 95 80 77 82 93
Average marks = 85.900002

Array best practices

  • Arrays are fixed size, hence always be cautious while accessing arrays. Accessing an element that does not exists is undefined. You may get a valid value or the program may crash.For example, consider the below program.
    int array[5]; // Declare an integer array of size 5
    
    /* Accessing sixth element of array which is undefined. */
    array[5] = 50;
    
    /* Accessing -1th element of array is undefined */
    array[-1] = 10;
    
  • Always take care of you loops when wiring it up with arrays. Be sure that the loop does not cross array index bounds.For example, consider the below loop that seems good but exceeds array index bounds.
    #include <stdio.h>
    #define SIZE 5
    
    int main()
    {
        int array[SIZE]; // Declare an array of size 5
        int index;
    
        /*
         * Valid array index start from 0 and goes till 4.
         * However, the loop runs from 0 to 5 which exceeds
         * array index bounds and the result is undefined.
         */
        for(index=0; index<=SIZE; index++)
        {
            scanf("%d", &array[index]);
        }
    
        return 0;
    }

    To overcome above array index bound, either use index<SIZE or use index<=SIZE-1.

  • Always keep in mind that all array element store a value of similar type.

Practice more array programming exercises to learn more.