Can we assign a value to a given memory location?

后端 未结 7 2154
自闭症患者
自闭症患者 2021-02-05 23:07

I want to assign some value (say 2345) to a memory location(say 0X12AED567). Can this be done?

In other words, how can I implement the following function?



        
7条回答
  •  误落风尘
    2021-02-05 23:59

    As far as C is concerned, that's undefined behaviour. My following suggestion is also undefined behaviour, but avoids all the type-based and aliasing-based problems: Use chars.

    int a = get_value();
    char const * const p = (const char * const)&a;
    char * q = (char *)0x12345;
    
    memcpy(q, p, sizeof(int));
    

    Alternatively, you can access bytes q[i] directly. (This is the part that is UB: the pointer q was not obtained as the address-of an actual object or as the result of an allocation function. Sometimes this is OK; for instance if you're writing a free-standing program that runs in real mode and accesses the graphics hardware, you can write to the graphics memory directly at a well-known, hard-coded address.)

提交回复
热议问题