#include <stdio.h>
int main( void )
{
int num = 1;
char *b;
b = (char*) #
*(++b) = 2;
printf("%d\n",num);
return 0;
}
Explanation : When I compiled this code , I encountered "513" as an output.When I use a comment line for that line: `*(++b)=2;
输出转换为“1”。
Question 1: Why did I encounter "513" as an output ?
Question 1: Why did output change when use comment line that I implied ?
最佳答案
假设 int
是 32 位的,在您的系统上采用小端字节序,num
的表示形式是 0x00000001
,如下所示在内存中:
-----------------
| 1 | 0 | 0 | 0 |
-----------------
然后你将b
指向num
:
b
|
v
-----------------
| 1 | 0 | 0 | 0 |
-----------------
然后你执行 *(++b)=2;
,它递增 b
,取消引用递增的指针,并将 2 写入该位置。所以你现在有了。
b
|
v
-----------------
| 1 | 2 | 0 | 0 |
-----------------
所以现在 num
的表示是 0x00000201`,十进制是 513。
关于c - 使用指针类型转换时值发生莫名其妙的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53987898/