1,395 views
1 votes
1 votes

Pls explain the o/p of this code:

O/p:2,2

main(void) {
    
    char a,*b=&a,**c=&b;
    a=2;
    **c=2;
    b=(int *)**c;
    printf("%d %d",a,b);
    return 0;
}

1 Answer

3 votes
3 votes

char a,*b=&a,**c=&b;
a=2;
**c=2;

b=(int *)**c;

Let address of a be 1000 and b be 1001 and c be 1009. 

b = &a; b now contains 1000.  (Don't get confused with * as it is part of char * and there is no dereferencing here)

c = &b; So, c now contains 1001.

a = 2; 2 is copied to memory location 1000.

**c = 2; //c contains 1001 and 1001 memory location now contains 1000. Since there is **, we go to memory location 1000, and because c is char**, a byte of memory storing 2 is copied to memory location 1000. (which makes a = 2)

b = (int *) **c;

**c returns 2 due to previous assignment. Now (int *) does a type conversion which makes 2 an address (nothing happens here, compiler just treats 2 as an address). So, now b contains 2. 

So, printf a,b, prints 2,2. But assigning integer values to pointers is a bad because dereferencing that location using *, should result in segmentation fault as that shouldn't be a valid memory location. 

Related questions

2 votes
2 votes
3 answers
1
Laahithyaa VS asked Sep 9, 2023
895 views
. What will be the value returned by the following function, when it is called with 11?recur (int num){if ((num / 2)! = 0 ) return (recur (num/2) *10+num%2);else return 1...