Can an address be assigned to a variable in C?

2020-03-05 02:37发布

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?

9条回答
兄弟一词,经得起流年.
2楼-- · 2020-03-05 03:21

It's not possible, maybe possible with compiler extensions. You could however access memory at an address you want (if the address is accessible to your process):

int addr = 7200;
*((int*)addr) = newVal;
查看更多
干净又极端
3楼-- · 2020-03-05 03:21

I think '&' in &a evaluates the address of i at the compile time which i think is a virtual address .So it is not a Lvalue according to your compiler. Use pointer instead

查看更多
在下西门庆
4楼-- · 2020-03-05 03:30

Use ldscript/linker command file. This will however, assign at link time, not run time.

Linker command file syntax depends largely on specific compiler. So you will need to google for linker command file, for your compiler.

Approximate pseudo syntax would be somewhat like this:

In linker command file:
.section start=0x1000 lenth=0x100 myVariables
In C file:
#pragma section myVariables
int myVar=10;
查看更多
登录 后发表回答