0
0
Power-electronicsHow-ToBeginner · 3 min read

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 integer integer_value to a pointer of the specified type.
  • type: The data type the pointer will point to, such as char, 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 volatile when accessing hardware registers, leading to compiler optimizations that break code.
  • Assuming the integer fits in a pointer without using uintptr_t or intptr_t for 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

ConceptDescription
(type *)integer_valueCast integer to pointer of given type
uintptr_tUnsigned integer type guaranteed to hold pointer
volatileUse for hardware registers to prevent optimization
Pointer alignmentEnsure 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.