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

后端 未结 7 2013
梦如初夏
梦如初夏 2020-12-19 17:26

I have the following piece of code:

#include 
#include 
int main(int argc, char *argv[])
{
  int n = 260; 
  int *p = &n;
         


        
7条回答
  •  醉话见心
    2020-12-19 18:00

    Considering 32 bit systems, 256 will be represented in like this.

    00000000 (Byte-3)   00000000 (Byte-2)    00000001(Byte-1)     00000100(Byte-0)
    

    Now when p is typecast-ed to a char pointer, the label on the pointer changes, but the memory contents don't. It means earlier p could have access 4 bytes, as it was an integer pointer, but now it can only access 1 byte as it is a char pointer. So, only the LSB gets changes to zero, not all the 4 bytes.

    And it becomes

    00000000 (Byte-3)   00000000 (Byte-2)    00000001(Byte-1)     00000000(Byte-0)
    

    Hence, the o/p is 256.

提交回复
热议问题