Arrays in C

An array is a way to group similar things, like storing a bunch of numbers of the same kind. For example, consider wanting to keep track of 5 integer numbers. If you were to store these 5 numbers using 5 separate integer variables, it would be difficult to manage and access them individually. However, arrays simplify this by allowing you to store all 5 numbers as a unified list, providing an organised and efficient solution.

With and without array

Storing values in separate variables results in non-contiguous memory locations. In this image, there are 4 elements: 12, 42, 65, and 43. When storing them in different variables, the programmer has to maintain all the variables and access these elements using their respective variables. This makes accessing the values more complex, especially as the number of elements increases. However, in an array, the memory locations are contiguous, as the array is shown in the image, arr[5] here 5 specifies the number of elements needed, to access a particular element index number is needed. index numbers start from 0, so it ends at n-1 where n is number of elements in an array. This means accessing elements is much easier, as you can simply use the index of the element to find it.

Here is a sample program of handling integer type of array:

#include <stdio.h>
int main()
{
      int i;
      // declare array of integers
      int arr[5] = {23, 45, 55, 21, 76};
      
      printf("printing array of integers:\n");
      for (i = 0; i < 5; i++)
      {
            printf("%d\n", arr[i]);
       }
}

output:

printing array of integers:
23
45
55
21
76

Note: while declaring arrays like this:- arr[5], here the number of elements specified in [ ] should be constant and not a variable like this:- arr[a]. A variable in [ ] can be given only at the time of accessing an index.

Here is another example for array of characters:

#include <stdio.h>
int main()
{
      int i;
      // declare array of integers
      char arr[5] = {'a', 'b', 'c', 'd', 'e'};
      
      printf("printing array of integers:\n");
      for (i = 0; i < 5; i++)
      {
            printf("%c\n", arr[i]);
       }
}

output:

printing array of integers:
a
b
c
d
e

Memory handling in array of integers and array of characters:

arrays in C

The only difference in integer and character is that the memory locations. In array of integers you can see that address locations increase with +4, as the size of each element is 4 bytes in integer array. Whereas in character array address locations increase with +1, as the size of each element is 1 byte in character array. When an index value with 1, arr_i[1] take to the memory location 0x1004 and for arr_c[1] take to the memory location 0x1001. So the programmer need both bother about the address locations as the index value will automatically take a specific element.

In the above programs values to array is assigned with fixed values. These are static values and user have no control over it, some changes in code can lead to take inputs from user as shown in below program.

#include <stdio.h>

int main()
{
        int arr[5];
        int i;

        printf("enter 5 integers:\n");
        /* take inputs from user */
        for (i = 0; i < 5; i++) {
                scanf("%d", &arr[i]);
        }

        printf("entered elements: ");
        for (i = 0; i < 5; i++) {
                printf("%d, ", arr[i]);
        }
}

input:

enter 5 integers:
4
5
6
7
8

output:

entered elements: 4, 5, 6, 7, 8,

Rules of handling an array

1. Intialising array:
valid initialisations:
int arr[10];
int arr[5] = {1, 2, 3, 4, 5};
int arr[5] = {1, 2, 3};

// assigned values can be less than array size.
char arr[ ] = {'o', 'n', 'e', 's', 'a', 'n', 'd', 'z', 'e', 'r', 'o', 's'};
// size is not given, array size is equal to number of elements assigned.

Invalid initialisations:
int arr[4] = {4, 34, 54, 44, 64};
// number of values assigned cannot be more than array size.
int arr2[ ] = arr1;
// assigning an array with another array is invalid.
int arr[size] = {1, 2, 3, 4, 5};
// using a valid at declaration is invalid.

2. Accessing an array
valid access:
char arr[5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};
arr[2] = ‘z’;
// accessing an element with a constant value is valid
char arr[5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};
int i = 2;
arr[i] = ‘z’;

// accessing an element with a variable is valid

invalid access:
int arr[5] = {‘a’, ‘b’, ‘c’, ‘d’};
arr[10] = ‘z’;

// accessing outside the array boundary leads to runtime errors.

size of an array

The size of an array can be determined by using sizeof operator just like we used for variable. sizeof operator returns the size of an array in bytes.

#include <stdio.h>

int main()
{
       int i_arr[5] = {7, 2, 5, 1, 7};
       char ch_arr[5] = {'a', 'e' , 'i', 'o', 'u'};

      printf("The size of i_arr is %d\n", sizeof(i_arr));
      printf("The size of ch_arr is %d\n", sizeof(ch_arr));
}

output:

The size of i_arr is 20
The size of ch_arr is 5

As the sizeof operator returns the size of array in bytes, when this value is divided by size of each element, it gives the number of elements in that array as shown below

#include <stdio.h>

int main()
{
        int arr[5] = {7, 2, 5, 1, 7};
        int num;

        num = sizeof(arr)/sizeof(arr[0]);
        printf("Number of elements in  arr is %d\n", num);
}

output:

Number of elements in  arr is 5

Sample program to add elements of an array

#include <stdio.h>

int main()
{
        int arr[5];
        int i, sum = 0;

        printf("enter 5 elements:\n");
        for (i = 0; i < 5; i++) {
                scanf("%d", &arr[i]);
        }

        for (i = 0; i < 5; i++) {
                sum += arr[i];
        }

        printf("The sum of integers is %d\n", sum);
}

input

enter 5 elements:
1
5
10 
20
30

ouput:

The sum of integers is 66

The above program uses two iterations to do the given task, but it is possible to finish it in one iteration as below:

#include <stdio.h>

int main()
{
        int arr[5];
        int i, sum = 0;

        printf("enter 5 elements:\n");
        for (i = 0; i < 5; i++) {
                scanf("%d", &arr[i]);
                sum += arr[i];
        }

        printf("The sum of integers is %d\n", sum);
}

input:

enter 5 elements:
21
31
41
51
61

output:

The sum of integers is 205

Copying array data to another array

An array cannot directly copy into another array in C. copying of array elements in c happens byte by byte. If the arr2 data have to copy into arr1 array, arr2 is the source, arr1 is destination and number of elements to copy from source to destination depends on requirement.

A sample program to copy array elements into another array

#include <stdio.h>

int main()
{
        int arr1[5];
        int arr2[5] = {1, 3, 4, 5, 6};
        int i;

        printf("copying arr2 elements to arr1\n");
        for (i = 0; i < 5; i++) {
                arr1[i] = arr2[i];
        }

        printf("arr1 elements after copying:\n");
        for (i = 0; i < 5; i++) {
                printf("%d ", arr1[i]);
        }
        printf("\n");
}

output:

copying arr2 elements to arr1
arr1 elements after copying:
1 3 4 5 6 

C provides an in built function to do this task and we don’t have to write this logic every time while copying array elements.

memcpy(dest, src, size);

dest: destination location to where the array elements to copy
src: source location from where the array elements to copy
size: number of bytes to copy

header file: string.h

Program to copy array elements using memcpy( )

#include <stdio.h>
#include <string.h>

int main()
{
        int arr1[5];
        int arr2[5] = {1, 3, 4, 5, 6};
        int i;

        printf("copying arr2 elements to arr1\n");
        memcpy(arr1, arr2, 5*sizeof(int));

        printf("arr1 elements after copying:\n");
        for (i = 0; i < 5; i++) {
                printf("%d ", arr1[i]);
        }
        printf("\n");
}

output

copying arr2 elements to arr1
arr1 elements after copying:
10 32 44 5 6 

Prev << Functions in C
Next >> Pointers with 1-D array