334 views

Consider the following declaration of $a$.

int a[100][200][30];


What will be the integer value of $a[50][300] - a[10][500]$?

### 1 comment

Ans given by me

1) Solving by counting no of elements between both pointers (addresses) -

int a[100][200][30];

a[50][300] – a[10][500] = (50 *  200 * 30 + 300 * 30) – (10 * 200 * 30 + 500 * 30) = 234000.

2) Solving by rules of pointer arithmetic -

Let b be the base address of a.

a[50][300] – a[10][500] = [ ( b + (50 *  200 * 30 + 300 * 30) * 4 ) – ( b + (10 * 200 * 30 + 500 * 30) * 4 ) ] / 4 = 234000.

https://onlinegdb.com/99kC3BmCZ2

Can u elaborate how 3D Array is stored in Memory

i know by default we use Row Major Order but how to visualize that

I'll be writing a[j][j][k] as A(i,j,k).

Element of a is stored as follows –

(In row major order) first A(0,0,0) is stored then A(0,0,1) then A(0,0,2) and so on upto A(0,0,29).

Then A(0,1,0) is stored then A(0,1,1) then A(0,1,2) and so on upto A(0,1,29).

Now this same pattern will follow till 199th row A(0,199,0), then A(0,199,1) and so on upto A(0,199,29).

All this was for A(0,j,k), similarly next we'll do with A(1,j,k) then A(2,j,k) and so on upto A(99,j,k).

Another way to visualise is –

In int arr1[30], this we visualize as an array of int of size 30.

arr1[0] will be 1st int, arr[1] will be 2nd int, and so on.

In int arr2[200][30], this we visualize as an array of type x of size 200. Here, x is array of 30 int.

arr2[0] will be 1st x, arr2[1] will be 2nd x, and so on.

In int arr3[100][200][30], this we visualize as an array of type y of size 100. Here, y is an array of 200 x.

arr3[1] will be 1st y, arr[2] will be 2nd y, and so on.

Here, we know that,

a is a pointer to 6000 Integers (or 200x30 array).

*a means it is a pointer to 30 integers.

**a is a pointer to integer.

we know that “element” in pointer arithmetic depends on type of pointers.

So, basically element here is just an integer.

Now come to the arithmetic….

a[50][300]

a+1 = 1000+6000 =7000

a+50 = 1000+ (50x6000) = 301000

*(a+50) = 301000 but now it’s pointer to 30 int.

*(a+50)+300 = 301000 + (30x300) = 310000

Same for a[10][500]

a+10 = 1000 +  (10x6000) = 61000

*(a+10) = 61000 now it’s also pointer to 30 int.

*(a+10)+500 = 61000 + (30x500) = 76000

So, finally ,

a[50][300]−a[10][500] = 310000 – 76000 = 234000

310000 we got is Address of Int at a[50][300]. Similarly 76000  is of a[10][500]

After subtracting, why are we not dividing by 4 because block pointed is integer? So block is 4B.

If we divide by 4 then it mean b/w these two addr there are 58500 elements of 4B(int).

Does Integer value in between, in question play a role in this doubt?

31000 is not address of a[50][300].

a[50][300] is the address of 31000th element of array a.