Pointer to Array or Array Pointer
Pointer to an Array in c, is a pointer variable which points to an array. It is also called Array pointer.
In c, Array name is also a constant pointer, which points to base address or first element of an array.
Syntax
<data_type> <array_variable>[size_of_array];
<data_type> *<pointer_variable>;
*pointer_variable = array_variable;
Example
#include<stdio.h>
void main()
{
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Points to first element or base address of array
int *pntr = a;
}
Get Array Elements Using Pointer
Accessing and output array values using pointers is really easy, In below example, there are two ways to get array elements using pointer in c.
#include<stdio.h>
void main()
{
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *pntr = a; // Points to first element or base address of array
// 1st way to get array values
printf("\n 1st way\n");
for(int i = 0; i < 10; i++)
{
printf("%d ", (pntr[i]));
}
printf("\n 2nd way\n");
// 2nd way to get array values
for(int i = 0; i < 10; i++)
{
printf("%d ", *(pntr+i));
}
}
Pointer Array to Array
Pointer array is a pointer variable with array points to another array.
Syntax
<data_type> <array_variable>[size_of_array];
<data_type> (*<pointer_variable>)[size_of_array];
pointer_variable = array_variable;
Example
#include<stdio.h>
void main()
{
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int (*pntr)[10]; // Pointer array to 10 elements
pntr = a;
for (int i = 0; i < 10; i++)
{
printf("%d ", (*pntr)[i]);
}
}
Pointers to 2D Arrays
Pointer can easily deal with multidimensional array like 2D, 3D arrays.
#include<stdio.h>
void main()
{
int a[3][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int (*pntr)[3][4] = &a;
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
printf("%d ", (*pntr)[row][col]);
}
printf("\n");
}
}