int main(){
int a, b;
char *cp;
a = 511;
cp = &a;
b = *cp;
*cp = 10;
printf("%d %d %d", a,b,*cp);
return 0;
}
The output for the above code is 266 -1 10 I understood how a = 266, this is because the first byte of a is replaced with the binary eqivalent of 10(*cp = 10) that makes a = 0000 0001 0000 1010 . But I am not able to understand why b is -1. In the line b = *cp, *cp in binary is 1111 1111 and this is copied to b, but why the end value is -1?
To understanf the output try this simple demonstration program.
Its output is
It seems the pointer
cpassigned likepoints to the less significant byte of the onbject
athat contains the value0xff.Also it seems that the type
charbehaves as the typesigned charin the compiled program. In this case the value0xffinterpreted as a value of an object of the typecharinternally represents the value-1. And this value is assigned to the variablebSo the variable
bhas the value-1or in hexadecimal like0xffffffff(provided thatsizeof( int )is equal to4) due to the propagating the sign bit according to the integer promotions.Then this byte is overwritten
So now the variable a internally has this value
0x10a(10in hexadecimal is equal to0x0a) And in decimal the value is equal to266.As a result in this call of
printfthere are outputted
athat is equal to266,bthat is equal to-1and the byte of the variableapointed to by the pointercpthat is equal to10.