将int指针转换为char指针会导致C中的数据丢失? [英] Casting int pointer to char pointer causes loss of data in C?

查看:226
本文介绍了将int指针转换为char指针会导致C中的数据丢失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

#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;
}

程序的输出结果为n = 256. 我可能会明白为什么会这样,但是我不确定. 有人可以给我一个清晰的解释吗?

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?

非常感谢.

推荐答案

int 260(= 256 * 1 + 4)在内存中看起来像这样-请注意,这取决于

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

通过使用char指针,您指向第一个字节并将其更改为0x00,这会将int更改为256(= 256 * 1 + 0).

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

这篇关于将int指针转换为char指针会导致C中的数据丢失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆