Skip to main content

Pointer to an array in C

Pointer to an Array

  • A pointer to an array is a pointer that points to the first element of an array.

  • In C, an array name can be treated as a pointer to the first element of the array.

The syntax for declaring a pointer to an array is as follows:

data_type (*ptr)[size];

Here, ptr is a pointer to an array of size elements of data type data_type.

For example, consider the following declaration:

int (*ptr)[5];

Explanation

  • This declares ptr as a pointer to an array of 5 integers.
  • You can use pointer to an array to access the elements of an array or to pass an array to a function.
  • When you use a pointer to an array, you dereference it to access the elements of the array.

For example, consider the following code:

int arr[5] = {10, 20, 30, 40, 50};
int (*ptr)[5] = &arr;
printf("%d\n", (*ptr)[2]);

Here, ptr points to the first element of the arr array, and we dereference it to access the third element of the array, which is 30.

Pointer to an Array - Example 1

Example of using a pointer to an 1D array:

#include <stdio.h>

int main(void)
{
int arr[5] = {10, 20, 30, 40, 50};
int(*ptr)[5] = &arr; // ptr is a pointer to an array of 5 integers

// Accessing elements of the array using the pointer
printf("The third element is: %d\n", (*ptr)[2]);

return 0;
}
Output:

Explanation

  • ptr is a pointer to an array of 5 integers.
  • The assignment ptr = &arr makes ptr point to the first element of the arr array.
  • The statement (*ptr)[2] dereferences the pointer ptr and accesses the third element of the array.

Pointer to an Array - Example 2

Example of using a pointer to an 2D array:

#include <stdio.h>

void printArray(int (*ptr)[3], int rows)
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", ptr[i][j]);
}
printf("\n");
}
}

int main(void)
{
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
int(*ptr)[3] = arr;

printf("The 2D array elements are:\n");
printArray(ptr, 2);

return 0;
}
Output:

Explanation

  • ptr is a pointer to an array of 3 integers, and arr is a 2D array of size "2 x 3".
  • The assignment ptr = arr makes ptr point to the first element of the arr array.
  • The function printArray takes a pointer to an array of 3 integers and the number of rows as arguments.
  • Inside the function, a nested loop is used to print the elements of the 2D array.
array name

In C, an array name can be treated as a pointer to the first element of the array.