241 views
1 votes
1 votes
#include <stdio.h>

int main()
{
    int arr[5], brr[5][5], crr[5][5][5];
    int i,j,k;
    for(i=0;i<5;i++)
    arr[i] = i;
    
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
            brr[i][j] = i+ j;
        }
    }
    
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
            for(k=0;k<5;k++)
            {
                crr[i][j][k] = i+j+k;
            }
        }
    }
    int *ptr1, **ptr2, ***ptr3;
    
    ptr1 = crr;
    printf("%d", *(ptr1+3));
    return 0;
}

Why it is printing the value inside the array?

As per my knowledge, crr means BA of 0th 2D array as crr is 3D array, and by 

ptr1 = crr;

means, ptr1 is having BA of 0th 2D array of crr. and (ptr1 + 3) means jumping to 3rd 2D array. After that *(ptr1 + 3 ) means BA of 0th 1D array of 3rd 2D array. So, it should print BA of 0th 1D array of 3rd D array but it is directly printing the value which is stored at the BA of 0th 1D of 3rd 2D array.

why?

1 Answer

0 votes
0 votes
Your analysis is partially correct, regarding ptr pointing to the 3rd 2D array,

ptr + 3 = ptr + (y * z * sizeof(int) * 3), where y and z are sizes of 2nd and 3rd dimension of crr (In our case, y = z = 5)

So, ptr + 3 = ptr + 5 * 5 * 3 * sizeof(int)

Since we can think memory as a linear array, the numbers are arranged as follows,

crr[0][0][0], crr[0][0][1], crr[0][0][2], crr[0][0][3], crr[0][0][4], crr[0][1][0] ...

Now, If you calculate the indices where ptr+ 3 points to, you can clearly see it is crr[3][0][0]

Since ptr is only a Single pointer (only one level of redirection is used)

Related questions

0 votes
0 votes
2 answers
1
Debargha Mitra Roy asked Apr 10
100 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
3 votes
3 votes
3 answers
2
Laxman Ghanchi asked May 19, 2023
1,157 views
#include<stdio.h void print(int n) { printf("Hello "); if(n++ == 0) return ; print(n); n++; } int main() { void print(); print(-4); }How many times printf execute?? And H...
0 votes
0 votes
1 answer
3
Laxman Ghanchi asked May 19, 2023
684 views
#include<stdio.h>void print(int n){ printf("Hello "); if(n++ == 0) return ; print(n); n++;}int main(){ void print(); print(-4);}