Monday, 20 February 2012

What is the equivalent pointer expression for referring an element a[i][j][k][l], in a four dimensional array? | C Programming

Consider a multidimensional array a[w][x][y][z].
In this array, a[i] gives address of a[i][0][0][0] and a[i]+j gives the address of a[i][j][0][0]
Similarly, a[i][j] gives address of a[i][j][0][0] and a[i][j]+k gives the address of a[i][j][k][0]
a[i][j][k] gives address of a[i][j][k][0] and a[i][j][k]+l gives address of a[i][j][k][l]
Hence a[i][j][k][l] can be accessed using pointers as *(a[i][j][k]+l)
where * stands for value at address and a[i][j][k]+l gives the address location of a[i][j][k][l].
Program: Example program to illustrate pointer denotation of multi-dimensional arrays.
#include<stdio.h>
#include<string.h>
int main() {
int a[3][3][3][3];
//it gives address of a[0][0][0][0] .
printf(" \n address of array a is %u", a);
printf("\n address of a[2][0][0][0] is %u ,given by a[2], %u given by a+2", a[2], a + 2);
printf("\n address of a[2][2][0][0] is %u ,given by a[2][2], %u given by a[2]+2", a[2][2], a[2] + 2);
printf("\n address of a[2][2][1][0] is %u ,given by a[2][2][1] , %u given by a[2][2]+1", a[2][2][1], a[2][2] + 1);
return 0;
}
Output:
address of array a is 65340
address of a[2][0][0][0] is 65448, given by a[2] , 65448 given by a+2
address of a[2][2][0][0] is 65484, given by a[2][2] ,65484 given by a[2]+2
address of a[2][2][1][0] is 65490, given by a[2][2][1] , 65490 given by a[2][2]+1
Explanation:
This output may differ from computer to computer as the address locations are not same for every computer.