memory address literal

夙愿已清 提交于 2020-01-03 13:09:35

问题


Given a literal memory address in hexadecimal format, how can I create a pointer in C that addresses this memory location?

Memory addresses on my platform (IBM iSeries) are 128bits. C type long long is also 128bits.

Imagine I have a memory address to a string (char array) that is: C622D0129B0129F0

I assume the correct C syntax to directly address this memory location:

const char* const p = (const char* const)0xC622D0129B0129F0ULL

I use ULL suffix indicate unsigned long long literal.

Whether my kernel/platform/operating system will allow me to do this is a different question. I first want to know if my syntax is correct.


回答1:


Your syntax is almost correct. You don't need one of those const:

const char* const p = (const char*)0xC622D0129B0129F0ULL

The const immediately before p indicates that the variable p cannot be changed after initialisation. It doesn't refer to anything about what p points to, so you don't need it on the right hand side.




回答2:


There is no such thing like an address literal in C.

The only thing that is guaranteed to work between integers and pointers is cast from void* to uintptr_t (if it exists) and then back. If you got your address from somewhere as an integer this should be of type uintptr_t. Use something like

(void*)(uintptr_t)UINTMAX_C(0xC622D0129B0129F0)

to convert it back.

You'd have to include stdint.h to get the type uintptr_t and the macro UINTMAX_C.



来源:https://stackoverflow.com/questions/3593985/memory-address-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!