My exact question is that there is any provision in c
and c++
to assign a value explicitly to particular address for example suppose I want to stor
You can do it like this:
*(int *)0x1846010 = 20; // store int value 20 at address 0x1846010
Retrieving works similar:
int x = *(int *)0x1846010;
Note that this assumes that address 0x1846010 is writable - in most cases this will generate an exception like Access violation writing location 0x01846010
.
P.S. For your interest, you can check given address writable or not at run-time by using the following (borrowed from here):
#include
#include
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;
}
As discussed here, typically you will only ever do this kind of thing for embedded code etc where there is no OS and you need to write to specific memory locations such as registers, I/O ports or special types of memory (e.g. NVRAM
).