Home / Learn Chip Programming / Pointers and Memory-Mapped Hardware
Pointers and Memory-Mapped Hardware
A register is just a memory address. A pointer to that address is how C controls hardware.
Theory in plain words
What it is
A pointer holds an address. Cast an integer address to a volatile uint32_t * and read or write it to talk to a peripheral.
Why we use it
All driver code, DMA buffers, arrays, strings and callbacks use pointers. Misuse is the top cause of crashes.
How it works
Declare, assign, dereference (*p), add (p+1 moves by sizeof element), pass to functions to modify caller data, const-qualify what you do not change.
Where it is used
- Peripheral register access
- Buffers and strings
- Function pointers (callbacks, ISR tables)
Pointer playground
Pointer arithmetic is scaled by element size. Going outside the array is a classic bug.
#define REG32(a) (*(volatile uint32_t *)(a))
REG32(0x40020014) |= (1u << 5); // set bit 5 of a register
void copy(uint8_t *dst, const uint8_t *src, size_t n) { // const: we only read src
while (n--) *dst++ = *src++;
}
typedef void (*handler_t)(void);
handler_t table[3] = { on_button, on_timer, on_uart }; // function pointer table
table[1](); // call through a pointerfree(). Initialise pointers to NULL and check before use.Quick quiz
1. p + 1 where p is uint32_t* moves by how many bytes?
Scaled by the element size.
2. Why add volatile to a register pointer?
The value can change without the code touching it.
Common questions
p + 1 where p is uint32_t* moves by how many bytes?
4. Scaled by the element size.
Why add volatile to a register pointer?
So the compiler does not optimise away accesses. The value can change without the code touching it.