gpt4 book ai didi

c - 为什么指针的值在转换后会发生变化?

转载 作者:太空宇宙 更新时间:2023-11-04 02:34:26 25 4
gpt4 key购买 nike

代码:

int main(void) {
register int rsp asm("rsp");
int temp=rsp;

printf("\n (rsp)%p \n", rsp);
printf("\n (temp)%p \n", temp);
printf("\n (void*)(rsp)%p \n", (void*)rsp );
printf("\n (void*)(temp)%p \n", (void*)temp );

return 0;
}

输出:

 (rsp)0xffffcbe0

(temp)0xffffcbe0

(void*)(rsp)0xffffffffffffcbe0

(void*)(temp)0xffffffffffffcbe0

我怀疑这是一个愚蠢的问题,但为什么指针的值在转换后会发生变化?我试图转换为不同的类型,但我总是得到相同的偏移量。谢谢。

最佳答案

but why does value of pointer changes after cast?

intrspint,不是指针。

使用 "%p"int 的未定义行为。

printf("\n (rsp)%p \n", rsp);   // UB
printf("\n (temp)%p \n", temp); // UB

但让我们假设转换为 unsigned 的值是由 OP 打印的。

printf("\n (rsp)0x%x \n", (unsigned) rsp);   // (rsp)0xffffcbe0
printf("\n (temp)0x%x \n", (unsigned) temp); // (temp)0xffffcbe0

当代码将指针转换为 int 时,如 register int rsp asm("rsp");,它可能失去意义 @David Wohlferd .当将 int 转换为指针时,会出现各种转换机制,例如符号扩展以应对窄 int"%p" 具有特定于实现的格式。

要清楚:OP 的代码不一定会打印原始 asm("rsp") 的地址。 (编译器特定的扩展)。

C 提供了可选的整数类型 (u)intptr_t,它提供了从/到等效整数和对象指针的转换。要将对象指针保存为整数,请使用这些类型。不幸的是,C 缺少用于打印非 void* 指针和 (u)intptr_t 值的锁存打印说明符,因此在下面进行强制转换。

#include <stdint.h>
#include <stdio.h>

char *s = "rsp";
printf("pointer %p\n", (void *) s);

uintptr_t i_ptr = (uintptr_t) s;
printf("integer 0x%jX\n", (uintmax_t) i_ptr);

关于c - 为什么指针的值在转换后会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39427206/

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