Reputation: 45
How can I assign a specific address to an already stored variable?
#include <stdio.h>
void main()
{
int a = 10;
printf("%d\n%d\n", a, &a);
&a = 2300000;
}
Upvotes: 0
Views: 493
Reputation: 1038
You can actually set a specific address to a variable the following way:
int * address = (int *)0xADD4388; // some arbitrary address
int & refvar = *address;
cout << "refvar: " << (size_t)refvar << ", &refvar: " << (size_t)&refvar << endl;
refvar = 4; // assignment will write to a specific address
Upvotes: 0
Reputation: 630
The memory addresses that you see are not in fact actual physical memory addresses, but virtual addresses. every process receives its own virtual memory space and it is possible to have variables in a few processes with the same "address".
therefore changing the address cannot be done, and it is also meaningless to do so.
in unix, you can use posix_memalign to allocate an address that is aligned to a specific number, but it cannot be any address that you want, that is because C automatically aligns memory(for example padding of structs). memory can only be aligned to a number that is a power of 2.
Upvotes: 0
Reputation: 34568
You cannot change the address of a variable.The compiler does have facilities to assign an absolute memory address to a variable. Using pointer you can only point to some address. Like,
int *p;
p = (int*) 0x00010000;
Upvotes: 1
Reputation: 172378
No, there is no way by which you can assign an address to a variable. You can assign an arbitrary location ie., you can point to some address with a pointer like
int *ptr;
ptr = (int*)7000;
But changing or assigning a specific address is not possible.
Upvotes: 1