将地址写入指针

时间:2015-11-18 20:47:02

标签: c pointers memory dereference

我有一个指针char *a指向一块内存。我有另一个指向内存块的指针char *b。让我们说b指向地址0x10001111。我想把这个地址写入接下来的8个字节到a指向的内存块。简而言之,当我尊重a时,我应该获得接下来的8个字节的内存并且值= 0x10001111。我怎么做?这是一台x86_64机器。

我目前的代码:

static void write_add(void *a, char *b)
{                                                                                                                                                                                                                                      *(unsigned long *)a= (unsigned long)b;
 *(unsigned long *)a= (unsigned long)b; 
 return;
}

我在解除引用a时只看到0x00001111。为什么我看不到完整的地址?

2 个答案:

答案 0 :(得分:1)

为什么你会涉及一个单独的,不相关的不确定大小?如果你想将指针值精确地存储在8个字节中(假设值适合,则为8个字节),你可以这样拼写:

#include <stdint.h>
static void write_add(void *a, char *b) {
    *(uint64_t *) a = (uint64_t) b; 
}

你也可以使用memcpy(),但这看起来有点笨拙。

但请注意,C不保证指针值表示的大小。虽然系统上64位可能已足够,但您无法安全地认为它在每个系统上都足够了。

答案 1 :(得分:0)

unsigned long is not necessarily 64 bits on your platform. You can't make that assumption simply because you're on a x86_64 platform. I'm willing to bet it's actually 32 bits.

You should use uintptr_t instead as suggested by cad. This type is always defined to be a type that is big enough to contain a pointer on your platform.