Skip to main content

Accessing Arrays in C

Accessing Arrays

In C, elements of an array can be accessed by using their index.

The index of an array element is an integer value that starts from 0.

For example:

int arr[5] = {1, 2, 3, 4, 5};

First element of the array can be accessed with the following code:

int first_element = arr[0];

Second element of the array can be accessed with the following code:

int first_element = arr[1];

and so on...

  • It's important to remember that in C, array indices start from 0, not 1. So, if you have an array with n elements, the indices of its elements will range from 0 to n-1.

  • If you try to access an element with an index that's outside this range, you'll get an error or unexpected behavior.

Accessing Arrays - Example

Here's an example that demonstrates accessing array elements in C:

#include <stdio.h>

int main()
{
int arr[5] = {1, 2, 3, 4,
5}; // Declare and initialize an array of 5 integers
int i;

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

return 0;
}
Output:

Explanation

  • This program first declares and initializes an array of 5 integers.
  • Then, the program uses a for loop to iterate over all the elements of the array.
  • In each iteration, the loop prints the index and value of the current array element
  • Finally, the program returns 0 to indicate successful execution.

Accessing Out of Range Array Index

  • Accessing an array element with an index that's outside the range of valid indices (i.e., an out-of-bound index) can lead to undefined behavior.

  • This means that the program may produce unexpected results or crash.

For example:

#include <stdio.h>

int main()
{
int arr[5] = {1, 2, 3, 4, 5}; // Declare and initialize an array of 5 integers

printf("%d\n", arr[5]); // Accessing an out-of-bound index

return 0;
}
Output:

Explanation

In this code, the printf function tries to access the element of the array with index 5, which is outside the range of valid indices (0 to 4). The behavior of the program in this case is undefined.

tip

It's important to always check that the index you're using to access an array element is within the range of valid indices, to avoid accessing out-of-bound indices and resulting in undefined behavior.