Reputation: 43
I wrote a program to test pointer actions but I didn't get the logic behind output.
As if I use arr+1
then instead of 2nd location I get 7th and similar is the case with *arr+1
and I feel weird for *
expression is showing address not value.
CAN ANYONE EXPLAIN OUTPUT, PLEASE !
Program is :
#include<stdio.h>
int main()
{
static int arr[2][3][2] = {1,2,3,4,5,6,7,8,9,10,11,12};
int i,j,k;
printf("%d\t",arr);
printf("%d\t",*arr);
printf("%d\n",**arr);
printf("%d\n",***arr);
printf("%d\t",arr+1);
printf("%d\t",*arr+1);
printf("%d\n",**arr+1);
printf("%d\n",***arr+1);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<2;k++)
printf("%d %u \n",*(*(*(arr+i)+j)+k),&arr[i][j][k]);
printf("\n");
}
printf("\n");
}
return 0;
}
And OUTPUT is:
4202512 4202512 4202512
1
4202536 4202520 4202516
2
1 4202512
2 4202516
3 4202520
4 4202524
5 4202528
6 4202532
7 4202536
8 4202540
9 4202544
10 4202548
11 4202552
12 4202556
Upvotes: 3
Views: 109
Reputation: 12016
you declare a int [2][3][2]
array, which means that:
arr
is an int [2][3][2]
array, so you can only get a pointer from that type.arr[0]
, or *arr
is an int [3][2]
array, so you can only get a pointer from that type.arr[0][0]
, or **arr
is an int [2]
array, so you can only get a pointer from that type.arr[0][0][0]
, or ***arr
is an int
, so you can only get a int
value from that type.variations of this process will give similar outcome.
you always get a same base address because multidimensional arrays are flat in memory and dimension sizes are used for partitioning that flat memory.
int [2][2]
is like:
0, 1
2, 3
Where the numbers resemble the order of elements in memory, and the bidimensional display resemble the array's line/column access.
Upvotes: 2
Reputation: 19736
Your first 3 prints are showing you the same address but have different meanings (and types)-
arr
is the address of your entire 3d array, of type int***
(you cast the pointer to int, not a good practice since on some systems it may be bigger) *arr
is the address of the "flattened" 2d array of type int**
, effectively located at arr[0]
**arr
is the address of the twice "flattened" 1d array of type int*
, effectively located at arr[0][0]
***arr
finally brings you to an actual int value of arr[0][0][0]
Now you start pointer arithmetics, that's determined by the type of the pointer as mentioned abode and by the size of each dimension (which is known to the compiler). So:
arr+1
gives you the address of arr[1]
, which is removed from arr[0]
by the length of 2*3 int elements (6*4=24 here)*arr+1
gives you the address arr[0][1]
, which is removed from arr[0][0]
by the length of 2 int elements (2*4=8 here)**arr+1
gives you the address of arr[0][0][1]
, which is removed from arr[0][0][0]
by the length of one int element (4 here)***arr+1
gives you arr[0][0][1]
, which is simply 2
See also this answer - How are 3D arrays stored in C?
Upvotes: 1