Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

pointers

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.

like image 278
ipkiss Avatar asked Dec 04 '22 23:12

ipkiss


2 Answers

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).

like image 110
schnaader Avatar answered Feb 08 '23 23:02

schnaader


You're apparently working on a little-endian machine. What's happening is that you're starting with an int that takes up at least two bytes. The value 260 is 256+4. The 256 goes in the second byte, and the 4 in the first byte. When you write 0 to the first byte, you're left with only the 256 in the second byte.

like image 25
Jerry Coffin Avatar answered Feb 08 '23 23:02

Jerry Coffin