in Programming in C retagged by
1,315 views
1 vote
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

in Programming in C retagged by
1.3k views

1 comment

moved by
its not answer

cout << (long)*p << "\t" << (long)(*p+1) << "\t" << (long)(*p+2);

here + is used as unary operator or binary??? explain.
0
0

1 Answer

4 votes
4 votes
Best answer

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
by

3 Comments

Arjun since p is a pointer to pointer to int, then *p is an address and that address contains int value 1. So by reading the following lines :-
 " 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) "

 i am confused that whether *p is 1 is element and if not then what it is?
1
1
*p is 1 and that is the element stored in the array. But *p+1 is 5 and that is just 1+4 and not the 5 stored in the array.
2
2
@Arjun Sir what does this line means ​  p = (int**)b; is it type casting ? and in this example what did you assume either array indexing starting from 0 or 1.
0
0

Related questions