in Programming in C recategorized by
509 views
1 vote
1 vote

Can you see why the output of the following code is 256?

main ()
    {
        int a=0x1ff;
        char *careful= &a;
        *careful = 0;
        printf("%d", a);
    }
in Programming in C recategorized by
509 views

3 Comments

It is 2's complement representation of 0
0
0
That's clear but still there is something more to it :p.
0
0
wait. 0 in 2's complement is represented by all bits 0.
0
0

2 Answers

1 vote
1 vote

Thanks.

0 votes
0 votes
char is a signed type. It takes value from -128 to 127

Now, u r taking a value which is in int and pointing by a character pointer.Now u make the value pointed by char pointer is 0. Now, again trying to print that value to print in integer, which will be out of range. So, it gives an overflow and that makes 9th bit as 1.

1 comment

Partially correct.

Hint 1:Actually char points to 1 byte while integer stores value in 4 byte.

Hint 2: It can also act as a check to whether your machine is big-endian or little endian.
0
0

Related questions