Member-only story
Pointers in C and C++ for Arduino
When developing for the Arduino it is not often you need to get down and dirty with pointers. They are very useful, powerful and dangerous. When you start playing with pointers, the compiler assumes you know what you are doing and doesn’t check as much. It is easy to come unstuck if you forget what goes where. For me it was trying to dereference a void pointer…
I try to avoid using pointers, because I usually stuff it up, but sometimes they are necessary. For my benefit, I am now documenting all the details that I should know regarding pointers in C and C++.
Pointers — The “Easy” Bits
A pointer is a variable that stores the address of another variable. Say we define an unsigned integer variable, x and assign to it the value of 0:
uint8_t x = 0;
This variable x, will be stored somewhere in memory. To work out where, we can assign a pointer variable of the same type to x using the & operator. The asterix (*) in front of the pointer name is called the indirection operator and is used when declaring a pointer.
uint8_t *ptr_to_x = &x;
The * operator can also be used to get the contents of the variable that a pointer is pointing at. To demonstrate these concepts, consider the example code below.