1,094 views

The value returned by the following code is _____

int foo()
{
int a[] = { 10, 20, 30, 40, 50, 60 };
int *p = &a[1] , *q = &a[5] ;
return q-p;
}

1 comment

@Arjun Sir plz explain this.

int *p = &a[1] , *q = &a[5] ;
return q-p;


q-p is nothing but no of elements (of type (*q) or (*p) which is int here) in between q and p. which is 4.

P holds the address  of 2nd element and q holds  the address of  6th element...and each are of intiger types  ...if base address is 100...2nd element will be 102....and 6th element will be 110....it will return 8
int *p ; now P+1 is skip one element. Skipping 1 element doesnt mean skipping no of bytes. Even if it is char *C then also C+1 means skipping one charecter.

Note : size of int is compiler dependent. you cant say it is int so it will take 2 or 4 byte.
Yea size of int is compiler dependend.....that is ok...but q is holding address and p also...so they will return the difference of their address
exactly ! but compiler is giving 4 as ans

Assuming size of integer = 2 bytes and base address = 1000.

It can be interpreted as:

10 a 1000
20 a+1 1002
30 a+2 1004
40 a+3 1006
50 a+4 1008
60 a+5 1010

Then

p = a + 1 (or 1002)

q = a + 5 (or 1010)

Hence, q - p = (a + 5) - (a + 1) = 4 (or (1010-1002)/2 = 4)

p and q both are pointer variable p hold the address of (a+1) means address of  a[1] . q will  hold the address of (a+5) means &a[5].

let suppose base address of a is 100  and every integer will take 2 byte so &a[1]=102 and &a[5]=110.

so 110=102=8.

value will  return 8.

For simplicity, say each element takes 2B, and assume base address is 100.

element at address 100 = 10

element at address 102 = 20

element at address 104 = 30

element at address 106 = 40

element at address 108 = 50

element at address 110 = 60

NOTE: Confusion is commonplace here.

p points to 102, and q points to 110. BUT *p is 20 and *q is 60; which is NOT asked here.

q-p would be 110 - 102 = 8.

But each element is of 2B, so scale it down by a factor of 2.

=> 8/2

=> 4

You can simply think of it as how many places is q far apart from p.

1
529 views