In this section, we will see how pointers can be used to access a three-dimensional array.
POINTERS
AND 3D ARRAYS
In
this section, we will see how pointers can be used to access a
three-dimensional array. We have seen that pointer to a one-dimensional array
can be declared as
int arr[]={1,2,3,4,5);
int *parr;
parr = arr;
Similarly,
pointer to a two-dimensional array can be declared as
int arr [2] [2]={{1,2}, {3, 4}};
int (*parr) [2];
parr = arr;
A
pointer to a three-dimensional array can be declared as
int arr [2] [2]
[2]={1,2,3,4,5,6,7,8};
int (*parr) [2] [2];
parr = arr;
We
can access an element of a three-dimensional array by writing,
arr[i] [j] [k] = *(*(*
(arr+i)+j)+k)
Look
at the code given below which illustrates the use of a pointer to a
three-dimensional array.
#include <stdio.h>
#include <conio.h>
main()
{
int i,j,k;
int arr [2] [2] [2];
int (*parr) [2] [2] = arr;
clrscr();
printf("\n Enter the elements
of a 2 × 2 × 2 array:");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
for (k = 0; k < 2; k++)
scanf("%d", &arr[i]
[j] [k]);
}
}
awode printf("\n The elements
of the 2 × 2 × 2 narray are: ");
for (i 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
for (k = 0; k < 2; k++)
printf("%d", *(*(*
(parr+i)+j)+k));
}
}
return 0;
getch();
}
Output
Enter the elements of a 2 × 2 × 2
array: 1 2 3 4 5 6 7 8
The elements of the 2 × 2 × 2 array
are: 1 2 3 4 5 6 7 8
Note
In
the printf statement, you could also have used * (* (* (arr+i)+j)+k)) instead
of *(*(* (parr+i)+j)+k)).
Programming in C: Unit III (b): Pointers : Tag: : with Example C Program - Pointers and 3D Arrays
Programming in C
CS3251 2nd Semester CSE Dept 2021 | Regulation | 2nd Semester CSE Dept 2021 Regulation