+1 vote
122 views

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

main ()
{
int a=0x1ff;
char *careful= &a;
*careful = 0;
printf("%d", a);
}
| 122 views
0
It is 2's complement representation of 0
0
That's clear but still there is something more to it :p.
0
wait. 0 in 2's complement is represented by all bits 0.

+1 vote

Thanks.

by Junior (941 points)
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.
by Veteran (119k points)
0
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.