0

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;
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
Kunal B
  • 45
  • 5
  • 1. [`void main()` is incorrect](http://stackoverflow.com/q/204476/995714). It's a relic from a non-standard compiler. 2. To print addresses use [`%p`](http://stackoverflow.com/q/9053658/995714). Using incorrect format specifier invokes undefined behavior – phuclv Sep 13 '16 at 05:50
  • 1
    @LưuVĩnhPhúc No void main() is not incorrect, where did you get that idea from? Read the link you posted, for example the answers by Jonathan Leffler or me. Most other answers are incomplete, far too simplified or just plain bad. – Lundin Sep 13 '16 at 08:19
  • @LưuVĩnhPhúc main can be implementation defined. Thus void main is a valid main function. See the current standard: 5.1.2.2.1 Program startup – 2501 Sep 13 '16 at 08:36
  • @2501 There's not even any indication that this question is about a hosted system. 5.1.2.2.1 refers to hosted systems only. Which indeed may have implementation-defined forms, though the standard is unclear. – Lundin Sep 13 '16 at 08:55

3 Answers3

1

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;
msc
  • 33,420
  • 29
  • 119
  • 214
1

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.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

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.

monkeyStix
  • 620
  • 5
  • 10