Can an address be assigned to a variable in C?

poorvank picture poorvank · Nov 26, 2012 · Viewed 16.2k times · Source

Is it possible to assign a variable the address you want, in the memory?

I tried to do so but I am getting an error as "Lvalue required as left operand of assignment".

int main() {
  int i = 10;
  &i = 7200;
  printf("i=%d address=%u", i, &i);
}

What is wrong with my approach? Is there any way in C in which we can assign an address we want, to a variable?

Answer

docdocdoc9 picture docdocdoc9 · Nov 26, 2012

Not directly. You can do this though : int* i = 7200; .. and then use i (ie. *i = 10) but you will most likely get a crash. This is only meaningful when doing low level development - device drivers, etc... with known memory addreses.