Search code examples
c++arraysmemory-addressmemory-mapping

How do you create a reference to an array at a certain address?


In C++, it is possible to create variables that are references to memory addresses.

volatile uint8_t& PPUSTATUS = *(volatile uint8_t*)0x2000;

This can be useful for things like memory-mapped I/O or hardware reserved memory regions, especially for embedded systems.
You can even create pointers to memory regions.

volatile uint8_t*& FDS_WAV = *((volatile uint8_t**)0x4040);

However, is it possible to create a reference to an array at a memory address?


Solution

  • uint8_t(&FDS_WAV)[64] = (uint8_t(&)[64])(*(uint8_t**)0x4040);
    

    This will create an array of 64 uint8_t at address 0x4040.
    &FDS_WAV will return 0x00004040, and sizeof(FDS_WAV) will return 64.