Pointer to an Array:
A pointer is a very important concept of C language. We can create a pointer to store the address of an array. This created pointer is called a pointer to an array. A pointer to an array is useful when we need to pass a multidimensional array into a function.
Pointer to an array is also known as an array pointer. We are using the pointer to array to access the elements of the array. It is important to know how to create a pointer to an array when working on a multi-dimension array.
Declaration of a pointer to a 1D Array:
data_type (*var_name)[size_of_array];
Example,
int (*ptr)[5];
Here ptr is a pointer that can point to an array of 5 integers. Since subscript has higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses. Here the type of ptr is ‘pointer to an array of 5 integers’.
So let see a C program to understand how we can create a pointer to an array and how we can use it in our program.
#include<stdio.h>
#define ARRAY_SIZE 5
int main()
{
int arr[ARRAY_SIZE] = {1,2,3,4,5};
int i = 0;
// Pointer to an array of integers
int (*ptr)[ARRAY_SIZE];
// Points to the whole array arr.
ptr = &arr;
for(i=0; i< ARRAY_SIZE ; ++i)
{
printf(" arr[%d] = %d\n",i,(*ptr)[i]);
}
return 0;
}
Output:
pointer to an array in C
Array of pointers:
As we know an array is essentially a collection of elements of the same data types. All elements must be the same and store at the contiguous memory location.
So we can create an array of pointers, it is basically an array of the pointer variables. It is also known as pointer arrays.
Declaration of an array of pointers:
Example,
Here “arr” is an array of 5 integer pointers.
So let see a C program to understand how we can create an array pointer and how we can use it in our C program.
Output: