gpt4 book ai didi

c - 使用指针类型转换时值发生莫名其妙的变化

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:00 25 4
gpt4 key购买 nike

#include <stdio.h>
int main( void )
{
int num = 1;
char *b;

b = (char*) &num;
*(++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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com