How to Use Pointers in Arduino: Simple Guide with Examples
In Arduino, you use
pointers to store memory addresses of variables, allowing indirect access and modification of data. Declare a pointer with the * symbol, assign it the address of a variable using &, and access the value via *pointer.Syntax
To use pointers in Arduino, declare a pointer variable with the type it points to, followed by *. Assign it the address of a variable using &. Access or modify the value at that address using * (dereference operator).
- Type *pointerName; - declares a pointer to a variable of Type.
- pointerName = &variable; - assigns the pointer the address of variable.
- *pointerName - accesses the value stored at the pointer's address.
arduino
int value = 10; int *ptr = &value; // Access value via pointer int x = *ptr; // Change value via pointer *ptr = 20;
Example
This example shows how to declare a pointer to an integer, print the original value, change it using the pointer, and print the updated value.
arduino
#include <Arduino.h> int value = 5; int *ptr = &value; void setup() { Serial.begin(9600); delay(1000); // Wait for Serial Serial.print("Original value: "); Serial.println(value); *ptr = 15; // Change value using pointer Serial.print("Updated value via pointer: "); Serial.println(value); } void loop() { // Nothing here }
Output
Original value: 5
Updated value via pointer: 15
Common Pitfalls
Common mistakes when using pointers in Arduino include:
- Not initializing pointers before use, which can cause crashes.
- Dereferencing
nullor uninitialized pointers. - Confusing the address-of operator
&with the dereference operator*. - Modifying data through pointers without understanding the original variable's scope.
Always initialize pointers and ensure they point to valid memory before dereferencing.
arduino
int *ptr; // Uninitialized pointer void setup() { Serial.begin(9600); // Serial.println(*ptr); // WRONG: ptr not initialized, causes error static int value = 10; ptr = &value; // Correct initialization Serial.println(*ptr); // Prints 10 }
Output
10
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Declare pointer | Type *ptr; | Creates a pointer to a variable of Type |
| Assign address | ptr = &var; | Pointer stores address of var |
| Dereference | *ptr | Access or modify value at pointer address |
| Null pointer | ptr = nullptr; | Pointer points to nothing (safe initialization) |
| Pointer to const | const Type *ptr; | Pointer to read-only data |
Key Takeaways
Pointers store memory addresses and allow indirect access to variables in Arduino.
Always initialize pointers before using them to avoid errors or crashes.
Use the & operator to get a variable's address and * to access or change its value.
Be careful not to dereference null or uninitialized pointers.
Pointers can help manage memory efficiently but require careful handling.