How to Use Pointer to Array in C: Syntax and Examples
In C, a
pointer to an array is declared by specifying the pointer to the entire array type, for example, int (*ptr)[5] points to an array of 5 integers. You use it to access or modify the whole array via the pointer by dereferencing it, like (*ptr)[index].Syntax
To declare a pointer to an array, you specify the pointer with parentheses around the pointer name and the array size after it. For example:
int (*ptr)[5];declaresptras a pointer to an array of 5 integers.(*ptr)[index]accesses the element atindexin the array pointed to byptr.
c
int (*ptr)[5];
Example
This example shows how to declare a pointer to an array, assign it to an existing array, and access elements through the pointer.
c
#include <stdio.h> int main() { int arr[5] = {10, 20, 30, 40, 50}; int (*ptr)[5] = &arr; // Pointer to the whole array // Access elements using the pointer for (int i = 0; i < 5; i++) { printf("Element %d: %d\n", i, (*ptr)[i]); } // Modify an element through the pointer (*ptr)[2] = 100; printf("Modified element 2: %d\n", arr[2]); return 0; }
Output
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
Modified element 2: 100
Common Pitfalls
Common mistakes when using pointers to arrays include:
- Confusing
int *ptr(pointer to int) withint (*ptr)[5](pointer to array of 5 ints). - Not using parentheses correctly, which changes the meaning of the declaration.
- Trying to assign the pointer to just the first element instead of the whole array address.
Example of wrong and right declaration:
c
/* Wrong: ptr is pointer to int, not pointer to array */ int *ptr; int arr[5]; ptr = arr; // points to first element, not whole array /* Right: ptr is pointer to array of 5 ints */ int (*ptr)[5]; ptr = &arr; // points to whole array
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Pointer to array | int (*ptr)[N]; | Pointer to an array of N elements of type int |
| Assign pointer | ptr = &array; | Assign address of whole array to pointer |
| Access element | (*ptr)[index] | Access element at index in the array pointed to |
| Difference | int *ptr vs int (*ptr)[N] | Pointer to element vs pointer to whole array |
Key Takeaways
Use parentheses to declare a pointer to an array: int (*ptr)[size];
Assign the pointer to the address of the array: ptr = &array;
Access elements by dereferencing the pointer first: (*ptr)[index];
Do not confuse pointer to array with pointer to element.
Pointers to arrays allow passing or manipulating whole arrays efficiently.