int i=512;
char *c = (char *)&i;
c[0] =1;
printf("%d",i);
this displays “513”, it adds 1 to i.
int i=512;
char *c = (char *)&i;
c[1] =1;
printf("%d",i);
whereas this displays 256. Divides it by 2.
Can someone please explain why? thanks a lot
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Binary
The 32-bit number 512 expressed in binary, is just:
because 2 to the power of 9 is 512. Conventionally, you read the bits from right-to-left.
Here are some other decimal numbers in binary:
The Cast: Reinterpreting the Int as an Array of Bytes
When you do this:
you are interpreting the 4-byte integer as an array of characters (8-bit bytes), as you probably know. If not, here’s what’s going on:
takes the address of the variable
i.reinterprets it (or casts it) to a pointer to char type. This means it can now be used like an array. Since you know an
intis at least 32-bit on your machine, can access its bytes usingc[0], c[1], c[2], c[3].Depending on the endianness of the system, the bytes of the number might be laid out: most significant byte first (big endian), or least significant byte first (little endian). x86 processors are little endian. This basically means the number 512 is laid out as in the example above, i.e.:
I’ve grouped the bits into separate 8-bit chunks (bytes) corresponding to the way they are laid out in memory. Note, you also read them right-to-left here, so we can keep with conventions for the binary number system.
Consequences
Now setting
c[0] = 1has this effect:which is
2^9 + 2^0 == 513in decimal.Setting
c[1] = 1has this effect:which is
2^8 == 256in decimal, because you’ve overwritten the second byte 00000010 with 00000001Do note on a big endian system, the bytes would be stored in reverse order to a little endian system. This would mean you’d get totally different results to ones you got if you ran it on one of those machines.