How to Access Array Elements Using Pointer in C
In C, you can access array elements using a
pointer by pointing to the array's first element and then using pointer arithmetic like *(ptr + index) to get each element. The pointer moves through the array by adding the index to it, which accesses elements sequentially.Syntax
To access array elements using a pointer, you first assign the pointer to the array's first element. Then use *(pointer + index) to get the element at the given index.
pointer: a variable holding the address of the array's first element.index: the position of the element you want to access (starting from 0).*(pointer + index): dereferences the pointer at the offsetindexto get the element.
c
int arr[] = {10, 20, 30}; int *ptr = arr; // pointer to first element int value = *(ptr + 1); // accesses arr[1], which is 20
Example
This example shows how to use a pointer to access and print all elements of an integer array.
c
#include <stdio.h> int main() { int arr[] = {5, 10, 15, 20, 25}; int *ptr = arr; // pointer to first element int length = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < length; i++) { // Access element using pointer arithmetic printf("Element %d: %d\n", i, *(ptr + i)); } return 0; }
Output
Element 0: 5
Element 1: 10
Element 2: 15
Element 3: 20
Element 4: 25
Common Pitfalls
Common mistakes when accessing array elements using pointers include:
- Not initializing the pointer to the array's first element before using it.
- Accessing out-of-bounds elements by using an index outside the array size, which causes undefined behavior.
- Confusing
ptr[index]and*(ptr + index)— both work the same, but forgetting the dereference operator*leads to errors.
c
/* Wrong: pointer not initialized */ int *ptr; // printf("%d", *ptr); // Undefined behavior /* Right: pointer initialized to array */ int arr[] = {1, 2, 3}; int *ptr = arr; printf("%d", *(ptr + 1)); // Prints 2
Output
2
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Pointer to array | Points to the first element of the array | int *ptr = arr; |
| Access element | Use pointer arithmetic and dereference | *(ptr + i) or ptr[i] |
| Pointer arithmetic | Moves pointer by element size | ptr + 1 points to next element |
| Array name | Acts as pointer to first element | arr == &arr[0] |
Key Takeaways
Use a pointer initialized to the array's first element to access elements.
Access elements with pointer arithmetic: *(ptr + index) or ptr[index].
Avoid accessing elements outside the array bounds to prevent errors.
Array name can be used as a pointer to the first element.
Always ensure the pointer is properly initialized before dereferencing.