Pointers and Memory Simulation
Run C code one line at a time and watch memory cells and pointer targets change. Four examples cover pointer basics, arrays and pointer arithmetic, pass by value versus by address, and writing past the end of an array.
Loading the 3D scene
Controls
Code the yellow line just ran
Measurements
- Lines run
- 0
- Pointer value
- -
- Points to
- -
- Value read through it
- -
Try this
- Each box is four bytes of memory. The variable name is above, the address below, and the current value in the middle.
- Press Next line to run one line of code. When
int *p = &a;runs, the p box receives the address of a and a yellow arrow connects p to a. - Run
*p = 30;. The p box stays the same, but the value of a at the end of the arrow changes. The asterisk means "go to that address". - Switch the example to Arrays and pointer arithmetic.
p++adds 4 to the address, not 1, because it steps over one int. - In By value and by address, new boxes appear when a function is called. Passing a value changes only the copy. Passing an address changes the original.
- Run Writing past the array to the end. The loop runs once too often and overwrites the variable right after the array. C does not stop you.
How to read it
A variable sits somewhere in memory, and the number of that place is its address. A pointer is a variable whose value is that number. Reading p gives the address, and reading *p gives the value at that address.
A function's local variables are created on the stack when it is called and disappear when it returns. The function boxes appearing and vanishing in this lab show exactly that.
The addresses imitate the start of RAM on an STM32 (0x20000000) as an example. The real layout depends on the compiler and optimisation.
This lab is also available in Korean. More labs: all 3D labs.