</>EmbeddedInterview

What is a pointer?

EasyPointers & Memory

Short answer: A pointer is a variable whose value is the address of another object (or function). Its type says what kind of object is at that address, which decides how many bytes a dereference reads or writes and how far p + 1 moves.

int x = 10;
int *p = &x;     /* & gives the address of x; p now points to x */
*p = 20;         /* * dereferences: writes 20 into x */
printf("%p %d\n", (void *)p, *p);

Key facts

  • Size: a data pointer is 4 bytes on a 32-bit MCU (Cortex-M) and 8 bytes on 64-bit Linux (ARM64, x86-64), regardless of what it points to. On some 8-bit/16-bit MCUs (AVR, 8051) there are different pointer sizes for code and data memory.
  • Type matters: uint8_t * and uint32_t * may hold the same address, but *p reads 1 byte versus 4 bytes.
  • NULL: a pointer that points to nothing. Always initialise pointers, either to an object or to NULL.
  • Dereferencing an invalid pointer (NULL, freed, uninitialised, out of bounds) is undefined behaviour.

Why pointers are essential in embedded C

  • Accessing hardware registers at fixed addresses.
  • Passing large structures and buffers to functions without copying them.
  • Letting functions return several results (output parameters).
  • Callbacks (function pointers), linked structures, and DMA descriptors that hold addresses of buffers.

Reading declarations: int *p (pointer to int), int **pp (pointer to pointer to int), int *a[4] (array of 4 pointers), int (*a)[4] (pointer to an array of 4 ints), int (*f)(void) (pointer to a function).