ipkiss ipkiss - 2 months ago 7
C Question

Casting int pointer to char pointer causes loss of data in C?

I have the following piece of code:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n = 260;
int *p = &n;
char *pp = (char*)p;
*pp = 0;

printf("n = %d\n", n);
system("PAUSE");
return 0;
}


The output put of the program is
n = 256
.
I may understand why it is, but I am not really sure.
Can anyone give me a clear explanation, please?

Thanks a lot.

Answer

The int 260 (= 256 * 1 + 4) will look like this in memory - note that this depends on the endianness of the machine - also, this is for a 32-bit (4 byte) int:

0x04 0x01 0x00 0x00

By using a char pointer, you point to the first byte and change it to 0x00, which changes the int to 256 (= 256 * 1 + 0).