0
0
CHow-ToBeginner · 3 min read

How to Access Array Elements in C: Syntax and Examples

In C, you access array elements using the array[index] syntax, where index starts at 0 for the first element. You can also use pointer arithmetic like *(array + index) to get the same element.
📐

Syntax

To access an element in an array, use the syntax array[index]. Here, array is the name of the array, and index is the position of the element you want, starting from 0.

Alternatively, you can use pointer arithmetic: *(array + index) means the same as array[index].

c
element = array[index];
// or
element = *(array + index);
💻

Example

This example shows how to declare an array and access its elements using both index notation and pointer arithmetic.

c
#include <stdio.h>

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

    // Access using index
    printf("Element at index 2: %d\n", numbers[2]);

    // Access using pointer arithmetic
    printf("Element at index 2 using pointer: %d\n", *(numbers + 2));

    return 0;
}
Output
Element at index 2: 30 Element at index 2 using pointer: 30
⚠️

Common Pitfalls

Common mistakes when accessing array elements include:

  • Using an index outside the array bounds (less than 0 or greater than or equal to the array size), which causes undefined behavior.
  • Confusing 1-based indexing with 0-based indexing in C.
  • Forgetting that arrays decay to pointers but are not pointers themselves.
c
#include <stdio.h>

int main() {
    int arr[3] = {1, 2, 3};

    // Wrong: Accessing out of bounds
    // printf("%d\n", arr[3]); // Undefined behavior!

    // Correct: Access within bounds
    printf("%d\n", arr[2]); // Prints 3

    return 0;
}
Output
3
📊

Quick Reference

ConceptDescriptionExample
Array element accessUse square brackets with zero-based indexarray[0], array[1], ...
Pointer arithmeticAccess element by adding index to pointer*(array + 0), *(array + 1)
Indexing starts atFirst element is at index 0array[0]
Out of boundsAccessing invalid index causes undefined behaviorarray[-1], array[size]

Key Takeaways

Access array elements using zero-based index with array[index].
Pointer arithmetic *(array + index) accesses the same element as array[index].
Never access elements outside the array bounds to avoid errors.
Remember array indexing starts at 0, not 1.
Arrays and pointers are related but not the same in C.