如何在不触发警告的情况下将整数值转换为指针地址 [英] How to Cast Integer Value to Pointer Address Without Triggering Warnings

查看:143
本文介绍了如何在不触发警告的情况下将整数值转换为指针地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下变量

uint32_t Value = 0x80

0x80代表内存中的地址,例如.

0x80 represents an address in the memory e.g.

// Write 2 at address 0x80
*(uint32_t*)((uint32_t)0x80) = 2;

如何将Value转换为Pointer,使其指向0x80?

How can i cast Value to a Pointer, so it points to 0x80?

uint32_t *Pointer = ?? Value;

此:

(uint32_t*)(uint32_t)Value;

返回:

warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

推荐答案

要处理整数到 object 的指针转换,请使用可选的整数uintptr_tintptr_t类型.函数指针是另一回事.

To handle integer to object pointer conversion, use the optional integer uintptr_t or intptr_t types. Function pointers are a separate matter.

以下类型指定一个无符号整数类型,其属性是可以将指向void的任何有效指针转换为该类型,然后再转换回指向void的指针,结果将与原始指针C11dr相等7.20.1.4 1

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer C11dr 7.20.1.4 1

uintptr_t

然后将void *转换为所需的类型.

Then convert the void * to the desired type.

#include <stdint.h>
uintptr_t Value = 0x80;
uint32_t *Pointer = (void *) Value;


如果不是从有效的uint32_t *派生0x80,则结果为未定义的行为(UB).然而,听起来OP处于具有内存映射数据位置的平台上.


If 0x80 was not derived from a valid uint32_t *, the result in undefined behavior (UB). Yet it sounds like OP is on a platform with memory mapped data locations.

这篇关于如何在不触发警告的情况下将整数值转换为指针地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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