edited by
953 views
3 votes
3 votes

Consider the following code

int main(){
    char *str = "ABCDEF";
    printf("%d",fun(str));
    return 0;
}
int fun(int *p1){
    int *p2 = p1;
    while(*++p1);
    return (p2-p1);
}

The output of given program is_________. Assume object of data type int occupies 2 bytes.

edited by

1 Answer

0 votes
0 votes

First of all in line int fun(int *p) it should be int fun(int *p1)  Edit done

Now str is pointer to string constant which is typecasted to integer pointer in  fun(int *p1) therefore p1 and p2 are both integer pointers.

Line while(*++p1);  incements p1 pointer 2 bytes everytime till we reach the null value = 0 and this loop terminates.

p2-p1 = {addressof(p2) - address of(p1) } / 2     since integer occupies two bytes

p2 - p1 = -3   // p2 is at lower address and p1 is at higher address

-3 is returned and printed

Related questions

–2 votes
–2 votes
0 answers
2
Sunil8860 asked Sep 21, 2017
356 views
0 votes
0 votes
1 answer
4
VS asked Dec 14, 2017
925 views