在内存中明确地为特定地址/位置分配或访问值?

Vik*_*rma 1 c c++ memory

我确切的问题是,有任何规定c,并c++明确指定的值,以特定的地址,例如,假设我要存储200x1846010内存中的地址,我也想访问使用相同的地址(值0x1846010).

可能很容易,但如果可以,我真的很困惑如何做到这一点.

任何人都可以解释这是可能的,如果是,那么如何(有适当的例子),如果没有那么为什么?

提前致谢.

her*_*tao 7

你可以这样做:

*(int *)0x1846010 = 20;  // store int value 20 at address 0x1846010
Run Code Online (Sandbox Code Playgroud)

检索工作类似:

int x = *(int *)0x1846010;
Run Code Online (Sandbox Code Playgroud)

请注意,这假设地址0x1846010是可写的 - 在大多数情况下,这将产生类似的异常Access violation writing location 0x01846010.

PS为了您的兴趣,您可以使用以下内容(从此处借用)在运行时检查给定地址是否可写:

#include <fcntl.h>
#include <unistd.h>

int is_writeable(void *p)
{
    int fd = open("/dev/zero", O_RDONLY);
    int writeable;

    if (fd < 0)
        return -1; /* Should not happen */

    writeable = read(fd, p, 1) == 1;
    close(fd);

    return writeable;
}
Run Code Online (Sandbox Code Playgroud)

正如这里所讨论的,通常你只会为没有操作系统的嵌入式代码等做这种事情,你需要写入特定的内存位置,如寄存器,I/O端口或特殊类型的内存(例如NVRAM).