[µblog] Generic pointers in C

Arithmetic step size of a pointer

A pointer is a variable that holds an address. So, if we declare int *ptr, we are saying that ptr is a variable that holds the address of an integer. Its arithmetic step size is the size of an integer. If we increment it as in ptr++ it would be incremented sizeof(int) bytes. If it was pointer to a byte, char *ptr, its arithmetic step size would be 1 byte. That is, the arithmetic step size of a pointer is the size of the type it points to. What about void* ptr?

Generic pointers

A pointer of type void* is said to be a generic pointer since it can point to any address. It cannot be dereferenced and it does not have an arithmetic step size, so we can’t perform pointer arithmetics on pointers to void.

Generic pointers are very handy to define generic functions that can accept a wide range of different pointers as their input arguments. An example [1]:

#include <stdio.h>
void print_bytes(void* data, size_t length) {
  char delim = ' ';
  unsigned char* ptr = data;
  for (size_t i = 0; i < length; i++) {
    printf("%c 0x%x", delim, *ptr);
    delim = ',';
    ptr++;
  }
  printf("\n");
}
int main(int argc, char** argv) {
 int a = 9;
 double b = 18.9;
 print_bytes(&a, sizeof(int));
 print_bytes(&b, sizeof(double));
 return 0;
}

Output:

 0x9, 0x0, 0x0, 0x0
 0x66, 0x66, 0x66, 0x66, 0x66, 0xe6, 0x32, 0x40

Inside the print_bytes function a pointer to unsigned char was used to iterate over every single byte on the input data memory address, since its arithmetic step size is 1 byte.

References

[1] Extreme C. AMINI, Kamran. Packt, 2019.

Author: Antonio Giacomelli de Oliveira

Embedded Systems Engineer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: