952 views
1 votes
1 votes
#include <stdio.h>

int main(void)

{
    int i;
    char *p=(char *)&i;
    ++p;
    (*p)=2;
    printf("%d",i);
    return 0;
}

1 Answer

Best answer
4 votes
4 votes

First edit is int i = 0; //else unexpected results due to garbage value.

char *p=(char *)&i;
++p;

In memory int i is stored as : [0000 0000] [0000 0000] [0000 0000] [0000 0000]   --> Assuming Little endian system (Right to Left is LSB to MSB ) and int size as 4 bytes.

Here first char pointer p is made to point i but typecasted to char pointer so will fetch only 8 bits from LSB of int i.

++p; makes p point to next byte. Then p will point to highlighted bit below i.e from there next 8 bits as char is of size 1 byte.

[0000 0000] [0000 0000] [0000 0000] [0000 0000]

(*p)=2;

This makes changes in memory as follows : 

[0000 0000] [0000 0000] [0000 0010] [0000 0000]

Now if we try to print i its nothing but 512 as 9th bit from LSB is 1.

So output is 512.

selected by

Related questions

0 votes
0 votes
1 answer
1
Anirudh Kaushal asked Apr 4, 2022
261 views
#include<stdio.h int main() { char num = '\011'; printf("%d",num); return 0; }
3 votes
3 votes
1 answer
2
Khushal Kumar asked Jul 7, 2017
611 views
#include <stdio.h>int main(){ int i = 8; int p = i++*i++; printf("%d\n", p);}
1 votes
1 votes
2 answers
3
Khushal Kumar asked Jul 7, 2017
604 views
#include <stdio.h int x = 20; int f1() { x = x+10; return x;} int f2() { x = x-5; return x;} int main() { int p = f1() + f2(); printf ("p = %d", p); return 0; }
0 votes
0 votes
4 answers
4
anonymous asked May 14, 2018
314 views
main(){int a = 1; int b = 1; int c = a || b ; printf("a = %d b=%d\n",a,b); return 0;}