retagged by
1,313 views
1 votes
1 votes

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

retagged by

1 Answer

Best answer
4 votes
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

Related questions

4 votes
4 votes
1 answer
1
0 votes
0 votes
0 answers
2
`JEET asked Dec 13, 2018
224 views
Please help me in solving this question.Very confusing. Question No. 19. Made Easy Work Book.
1 votes
1 votes
1 answer
3
Balaji Jegan asked Jun 27, 2018
967 views
Can anyone please verify whether I have calculated the addresses correctly or not?
1 votes
1 votes
1 answer
4
Narayan Kunal asked Aug 24, 2014
638 views
If anybody have some note or link to the topic like NP related questions, Please provide. I have never been successful in answering these type of question. Any help will ...