How to Use Pointer with Array in C: Syntax and Examples
In C, you can use a
pointer to refer to the first element of an array by assigning the array name to the pointer. You can then access array elements by moving the pointer with arithmetic or using the pointer like an array with *(ptr + index) or ptr[index].Syntax
Here is the basic syntax to use a pointer with an array in C:
type *ptr = array;— Assigns the pointer to the first element of the array.*(ptr + i)— Accesses the element at indexiusing pointer arithmetic.ptr[i]— Another way to access the element at indexiusing pointer indexing.
c
int arr[] = {10, 20, 30}; int *ptr = arr; // Pointer points to first element int first = *ptr; // Access first element int second = *(ptr + 1); // Access second element int third = ptr[2]; // Access third element
Example
This example shows how to use a pointer to iterate over an array and print its elements.
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++) { 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 using pointers with arrays include:
- Not initializing the pointer to the array's first element before use.
- Accessing out-of-bounds elements, which causes undefined behavior.
- Confusing the array name and pointer variable — the array name is not a modifiable pointer.
Example of wrong and right usage:
c
#include <stdio.h> int main() { int arr[] = {1, 2, 3}; int *ptr; // Wrong: ptr not initialized // printf("%d\n", *ptr); // Undefined behavior // Right: initialize pointer ptr = arr; printf("First element: %d\n", *ptr); return 0; }
Output
First element: 1
Quick Reference
Tips for using pointers with arrays:
- Array name acts like a pointer to its first element.
- Use
ptr = array;to point to the start. - Access elements with
*(ptr + i)orptr[i]. - Pointer arithmetic moves in steps of the element size automatically.
- Always ensure pointer stays within array bounds.
Key Takeaways
A pointer can hold the address of the first element of an array using
ptr = array;.Access array elements via pointer arithmetic like
*(ptr + i) or pointer indexing ptr[i].Always initialize pointers before use to avoid undefined behavior.
Pointer arithmetic automatically accounts for element size in arrays.
Never access elements outside the array bounds using pointers.