I want to create an integer array array[3] in a specific address addr, and initialize the array with { 1, 3, 6 }. How can I do that?
int addr = 0x40000;
((int *)addr)[3] = { 1, 3, 6 }; //Error
You can't initialise an array at that location, and you can't even declare that there is one.
However, you can use a pointer to manipulate values already existing at that location.
In fact, you're pretty close:
int* addr = (int*)0x40000;
addr[0] = 1;
addr[1] = 3;
addr[2] = 6;
Technically, this may have undefined behaviour depending on where this 0x40000 comes from: performing pointer arithmetic (including via array subscripting like this) requires that you are navigating an object or array of objects, which must have been created by your program: if your integers were instead created by some other process (possible, despite virtual memory, if for example you're memory mapping some hardware registers) then this is not strictly the case. However, it will work on basically all hardware and is a common technique.
But if nothing currently exists at 0x40000 and you're trying to specify where a brand new C array will be allocated then, no, you cannot do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With