Reputation: 5370
I was at an interview in which they asked me:
What will happen if you compile the following code? Will it compile successfully? If yes, what will be the output?
static int a[ ] = {0,1,2,3,4};
int *p[ ] = {a,a+1,a+2,a+3,a+4};
int **ptr = p;
ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*++ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
++*ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
I has no answer. This was way more complex than the problems that I had solved.
Then they responded:
The output will be:
111
222
333
344
After going home also I could not actually understand how it worked. Could someone explain this to me? Any help Appreciated.
Upvotes: 3
Views: 90
Reputation: 2206
Lets denote the addresses of array a
with some arbitrary address numbers for better understanding (without taking the size of int into consideration).
a[] = {0,1,2,3,4}
address value
1000 = 0
1001 = 1
1002 = 2
1003 = 3
1004 = 4
Now int *p[ ] = {a,a+1,a+2,a+3,a+4};
is a array of pointers. So its basically keeping some address. lets assume some arbitrary address for this array too
address value
2000 = 1000 (a means address of a[0] and a+1 means address of a[1] and so on)
2001 = 1001
2002 = 1002
2003 = 1003
2004 = 1004
int **ptr = p;
is a pointer to another pointer. so its basically pointing to first address of array p
which is 2000
and has a value of 1000
.
ptr++;
advances the pointer ptr
by one step. So its now pointing to the 2nd address of p
which is 2001
with a value of 1001
.
Now printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
:
value of ptr
is 2001
and value of p
is 2000
(because p
means address of p[0]
). So the difference is 2001-2000 = 1
value of *ptr
is 1001
and value of a
is 1000
. So the difference is 1001-1000 = 1
value of **ptr
is 1. because ptr=2001
. *ptr = 1001
and **ptr = 1
(value at address 1001
)
Upvotes: 3