How to Cast Integer to Pointer in Embedded C: Syntax and Examples
In embedded C, you can cast an integer to a pointer using
(type *)integer_value. This is often used to access specific memory addresses directly by converting an integer address to a pointer type.Syntax
The syntax to cast an integer to a pointer in embedded C is:
(type *)integer_value: Casts the integerinteger_valueto a pointer of the specifiedtype.type: The data type the pointer will point to, such aschar,int, or a struct.integer_value: The integer representing the memory address you want to access.
c
(type *)integer_value;Example
This example shows how to cast an integer address to a pointer and read a value from that memory location. It simulates reading from a hardware register at a fixed address.
c
#include <stdio.h> #include <stdint.h> int main() { uintptr_t address = 0x20000000; // Example memory address volatile uint32_t *ptr = (volatile uint32_t *)address; // Cast integer to pointer // For demonstration, we cannot actually read this address safely, // so we just print the pointer value. printf("Pointer address: %p\n", (void *)ptr); // In real embedded code, you might do: // uint32_t value = *ptr; // printf("Value at address: %u\n", value); return 0; }
Output
Pointer address: 0x20000000
Common Pitfalls
Common mistakes when casting integers to pointers include:
- Using an invalid or unaligned address, which can cause crashes or undefined behavior.
- Forgetting to use
volatilewhen accessing hardware registers, leading to compiler optimizations that break code. - Assuming the integer fits in a pointer without using
uintptr_torintptr_tfor safe casting.
Example of wrong and right casting:
c
// Wrong: casting int directly without uintptr_t int addr = 0x20000000; int *ptr_wrong = (int *)addr; // May cause warnings or errors // Right: use uintptr_t for safe casting #include <stdint.h> uintptr_t addr_safe = 0x20000000; int *ptr_right = (int *)addr_safe;
Quick Reference
| Concept | Description |
|---|---|
| (type *)integer_value | Cast integer to pointer of given type |
| uintptr_t | Unsigned integer type guaranteed to hold pointer |
| volatile | Use for hardware registers to prevent optimization |
| Pointer alignment | Ensure address matches type alignment to avoid faults |
Key Takeaways
Use (type *)integer_value to cast an integer to a pointer in embedded C.
Prefer uintptr_t for storing integer addresses safely before casting.
Use volatile keyword when accessing hardware registers via pointers.
Ensure the integer address is valid and properly aligned for the pointer type.
Casting incorrectly can cause crashes or undefined behavior in embedded systems.