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

后端 未结 7 1999
梦如初夏
梦如初夏 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:10

    In C a pointer references a block of bytes based on the type associated with the pointer. So in your case the integer pointer refers to a block 4 bytes in size, while a char is only one byte long. When you set the char to 0 it only changes the first byte of the integer value, but because of how numbers are stored in memory on modern machines (effectively in reverse order from how you would write it) you are overwritting the least significant byte (which was 4) you are left w/ 256 as the value

    0 讨论(0)
提交回复
热议问题