C / CHAPTER 07
Addresses, borrowing, and lifetime
AdvancedUse pointers to update a caller’s object without crossing its lifetime or bounds.
By the end of this chapter
- Distinguish an address from its pointed value
- Use an output parameter intentionally
- Avoid dangling pointers
The idea
Bring array bounds and function knowledge. The address operator obtains a pointer to an existing object, and dereferencing accesses that object through the pointer. Passing a pointer still passes a value: the function gets a copy of the address, but both addresses can identify the same caller-owned object. This supports functions that intentionally update caller data without pretending an ordinary value parameter can do so.
A usable pointer must refer to a live object of an appropriate type, with valid alignment and a permitted access. A non-null pointer is not automatically valid. A local object ordinarily ends its lifetime when its block finishes, so returning its address does not preserve it. Array pointer arithmetic must remain within the array or its one-past position; the one-past pointer must never be dereferenced.
#include <stdio.h>
void addTwo(int *value){*value+=2;}
int main(void){int scores[]={4,7,9}; addTwo(&scores[1]); printf("%d %d\n",scores[0],scores[1]);}4 9
The copied address still identifies scores[1]. Dereferencing updates that element while the first element remains unchanged.
Try it yourself
Write a swap function using two int pointers; state that both pointers must identify live writable int objects.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING