Chapter 6. Pointers and References

Reasonably direct access to memory is one of C’s biggest features for folks who work on low-level problems like device drivers or embedded systems. C gives you the tools to micromanage your bytes. That can be a real boon when you need to worry about every bit of free memory, but it can also be a real pain to worry about every bit of memory you use. When you want that control, though, it’s great to have the option. This chapter covers the basics of finding out where things are located in memory (their address) as well as storing and using those locations with pointers, variables that store the address of other variables.

Addresses in C

We’ve touched on the notion of pointers when we discussed using scanf() to read in base types like integers and floats versus reading in a string as a character array. You may recall for numbers, I mentioned the required & prefix. That prefix can be thought of as an “address of” the operator or function. It returns a numeric value that tells you where the variable following the & is located in memory. We can actually print that location out. Take a look at ch06/address.c:

#include <stdio.h>

int main() {
  int answer = 42;
  double pi = 3.1415926;
  printf("answer's value: %d\n", answer);
  printf("answer's address: %p\n", &answer);
  printf("pi's value: %0.4f\n", pi);
  printf("pi's address: %p\n", &pi);
}

In this simple program, we create two variables and initialize them. We use a few printf() statements to show ...

Get Smaller C now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.