Explicitly assign or access values to or from specific address/location in memory?

前端 未结 3 1889
礼貌的吻别
礼貌的吻别 2021-01-16 07:03

My exact question is that there is any provision in c and c++ to assign a value explicitly to particular address for example suppose I want to stor

3条回答
  •  遥遥无期
    2021-01-16 07:53

    Yes.

    Assuming that 0x1846010 is a valid address to which you have write access, you can write:

    *(int*)0x1846010 = 20;
    

    And to access the stored value:

    printf("%d\n", *(int*)0x1846010);
    

    And if you actually do that in a program, it will probably crash, because 0x1846010 very probably isn't a valid address to which you have write access.

    Why exactly do you want to do this? How do you know (if you know) that 0x1846010 is a valid address?

    This assumes that the conversion of the integer value 0x1846010 to a pointer is even meaningful. The result of the conversion is implementation-defined, but is "intended to be consistent with the addressing structure of the execution environment".

提交回复
热议问题