views:

118

answers:

2

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.

+9  A: 

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.

Greg Hewgill
The compiler accepting it is a good place to start, but does not guarantee standards conformance. There are many extensions implemented in compilers. That said, yeah this looks correct.
Merlyn Morgan-Graham
No, this is undefined behavior. Only conversion to `void*` is supposed to give something correct and `uintptr_t` might be different from `unsigned long long` (though unlikely in this case)
Jens Gustedt
Jens is wrong - the behaviour is implementation-defined, *not* undefined
Christoph
A: 

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.

Jens Gustedt
-1: C99 only defines macros for minimum-width and greatest-width integer constants - there is no macro `UINTPTR_C()` in `stdint.h`
Christoph
@Christoph: Your second assertion is correct. I'll edit my answer accordingly.
Jens Gustedt
@Jens: removed downvote; fixed the missing `0x` as well...
Christoph
@Christoph: ok, thanks!
Jens Gustedt