Can an address be assigned to a variable in C?

前端 未结 9 2027
孤城傲影
孤城傲影 2021-01-06 05:28

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 assignmen

相关标签:
9条回答
  • 2021-01-06 05:47

    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.

    0 讨论(0)
  • 2021-01-06 05:50

    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;
    
    0 讨论(0)
  • 2021-01-06 05:54

    No.

    Even if you could, 7200 is not a pointer (memory address), it's an int, so that wouldn't work anyway.

    0 讨论(0)
  • 2021-01-06 05:57

    Not portably. But some compilers (usually for the embedded world) have extensions to do it.

    For example on IAR compiler (here for MSP430), you can do this:

    static const char version[] @ 0x1000 = "v1.0";
    

    This will put object version at memory address 0x1000.

    0 讨论(0)
  • 2021-01-06 05:57

    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

    0 讨论(0)
  • 2021-01-06 05:58

    There's probably no way to determine which address a variable will have. But as a last hope for you, there is something called "pointer", so you can modify a value on address 7200 (although this address will probably be inaccessible):

    int *i = (int *)7200;
    *i = 10;
    
    0 讨论(0)
提交回复
热议问题