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

后端 未结 7 2003
梦如初夏
梦如初夏 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 17:53

    I understood what exactly happens by changing value:

    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
      int n = 260; 
      int *p = &n;
      char *pp = (char*)p;
      *pp = 20;
    
        printf("pp = %d\n", (int)*pp);
      printf("n = %d\n", (int)n);
      system("PAUSE");  
      return 0;
    }
    

    The output value are 20 and 276

    So basically the problem is not that you have data loss, is that the char pointer points only to the first byte of the int and so it changes only that, the other bytes are not changed and that's why those weird value (if you are on an INTEL processor the first byte is the least significant, that's why you change the "smallest" part of the number

提交回复
热议问题