• retagged by
2,200 views
1 1 vote

Explain the output :-


int b[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
int** p;
p = (int**)b;
cout << (long)*p << "\t" << (long)(*p+1) << "\t" << (long)(*p+2);


//long is used to print the output in decimal format instead of hex

1 Answer

Best answer
4 4 votes

Here, b is a 2D array and it contains 3*4 = 12 elements. Suppose address of b starts from 1000. Now the elements will be stored as:

1000-3: 1
1004-7: 2
1008-11: 3
1012-15: 4
1016-19: 5
....
1045-48: 12

Now, we declare p as int** and initialize it to 1000, the base address of b. 

So, *p will have 1. (assuming a 32 bit architecture, on 64 bit architecture *p will be 8 bytes and the array element being int is only 4 bytes)

Now, *p+1, is pointer arithmetic. It will add 1 *sizeof(int) to *p. So, *p+1 will give 1 + 4 = 5. (This 5 is not the element 5 in the array)

Similarly, *p+2, will add 2*sizeof(int) = 2*4 = 8 to *p. So, *p+2 will give 1+8 = 9. 

These are all valid only on a 32 bit compiler. On a 64 bit compiler, if we use 

(long)*p

It will try to read 8 bytes from the start of the array. 
Since,
1000-3: 1
1004-7: 2

From 1000, the content of memory will be (assuming a little endian machine)
0000 0001 0000 0000 0000 0000 0000 0000 | 0000 0010 0000 0000 0000 0000 0000 0000

This value in binary will be 
0000 0010 0000 0000 0000 0000 0000 0000 0000 0001
= $2^{33} + 1 $
= $8589934593$

So, the output will be 
8589934593, 8589934597 and 8589934601

This output is entirely implementation dependent as it depends on the sizeof (int) and sizeof pointer and also depends on the endianness of the machine(if sizeof (int) is different from sizeof pointer) . 

For more details about pointer arithmetic you can see here:

http://gatecse.in/wiki/Chapter_3:_Pointers#Pointer_Arithmetic




 

• selected by
Position:
Show:

Related questions

0 0 votes
0 0 answers
475
475 views
`JEET asked Dec 13, 2018
475 views
Please help me in solving this question.Very confusing. Question No. 19. Made Easy Work Book.
0 0 votes
1 1 answer
774
774 views
saket jaiswal asked Jan 7, 2025
774 views
#include <stdio.h void swap(int x, int i, int j) { int *temp; temp = x[i]; x[i] = x[j]; x[j] = temp; } int main() { int a[6] = {1, 2, 3}; int (*p)[6] = &a; int *arr[3] ...
5 5 votes
1 answers 1 answer
1.9k
1.9k views
kd..... asked Apr 25, 2018
1,940 views
Why is it illegal initialization?#include<stdio.h #include<string.h main() { char *s[]={"Lakshya","cquest","brainq","cidol"}; char ss[]={(s+3),(s+2),(s+1),(s+0)}; char ...
1 1 vote
1 1 answer
1.6k
1.6k views
Balaji Jegan asked Jun 27, 2018
1,618 views
Can anyone please verify whether I have calculated the addresses correctly or not?