简体   繁体   English

将 int 转换为 int* 会发生什么?

[英]What happens when you cast an int to an int*?

int val{ 100 };
int* ptr1 = (int*)val;
int* ptr2 = ptr1 + 5;
std::cout << ptr2 << '\n' << (int)ptr2 << std::endl;

In this code example the result of (int*)val is 00000064 , but I don't understand why.在此代码示例中, (int*)val的结果是00000064 ,但我不明白为什么。 I also don't understand why (int)ptr2 is 120 .我也不明白为什么(int)ptr2120

Analyzing line per line:每行分析行:

int* ptr1 = (int*)val;

Assign the decimal value 100 to the pointer ptr1 ;十进制值100分配给指针ptr1

int* ptr2 = ptr1 + 5;

This instuction invokes undefined behaviour , the algebric operation over pointer is allowed only in array context.此指令调用未定义的行为仅在数组上下文中允许对指针进行代数运算。

std::cout << ptr2 << '\n' << (int)ptr2 << std::endl;

This instruction can print everything due to the previous undefined behaviour.由于先前未定义的行为,该指令可以打印所有内容。

The the result of (int*)val is 00000064 because is the representation of decimal value 100 in hexadecimal notation (int*)val的结果是00000064因为是十进制值100十六进制表示法

Step by step:一步步:

int* ptr1 = (int*)val;

After executing this instruction ptr1 has decimal value 100 (00000064 in hexadecimal).执行此指令后,ptr1 的十进制值为 100(十六进制为 00000064)。

int* ptr2 = ptr1 + 5;

Now ptr2 has the same memory adress of ptr1, shifted by 5 units.现在 ptr2 与 ptr1 具有相同的 memory 地址,移动了 5 个单位。 It is shifted by 5 * (4 bytes) = 20 bytes.它移动了 5 *(4 字节)= 20 字节。 The memory address represented by ptr2 is (00000078) This is the reason why (int)ptr2 is 120 (100 + 20). ptr2表示的memory地址为(00000078)这就是(int)ptr2为120(100+20)的原因。

Can this reasoning make sense?这种推理能说得通吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM