liveBook · Manning

Address-of operator

As explained in Modern C

The address-of operator is the C unary operator that produces a pointer to its operand's object or function.

The C address-of operator, &, produces a pointer containing an object’s address. Passing addresses lets a function operate on objects outside its local variables, as double_swap does with two double objects. section 11.1.1

   double_swap(&d0, &d1);

The call passes the addresses of d0 and d1, rather than copying their values into double_swap. section 11.1.1

void double_swap(double* p0, double* p1) {
  double tmp = *p0;
  *p0 = *p1;
  *p1 = tmp;
}


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":4}],[{\"line\":0,\"ch\":5},{\"line\":0,\"ch\":11}],[{\"line\":1,\"ch\":2},{\"line\":1,\"ch\":8}],[{\"line\":0,\"ch\":5},{\"line\":0,\"ch\":11}],[{\"line\":1,\"ch\":2},{\"line\":1,\"ch\":8}],[{\"line\":0,\"ch\":5},{\"line\":0,\"ch\":11}],[{\"line\":1,\"ch\":2},{\"line\":1,\"ch\":8}]]"}
!@%STYLE%@!

The pointer parameters receive those addresses; *p0 and *p1 designate the corresponding objects so the function can swap their contents. section 11.1.1

Keep these two uses of * distinct:

  • In a declaration such as double*, * creates a pointer type. section 11.1.1
  • In an expression such as *p0, * is the object-of operator: it dereferences the pointer and accesses its referred object. section 11.1.1
  • Using * with a null or indeterminate pointer has undefined behavior. section 11.1.1

Because addresses can be passed through different parts of a program, pointers also connect the address-of operator to memory state and aliasing. Two pointers may access the same object; except for character types, only pointers with the same base type may alias. section 12.3

Practice

Write a function that receives pointers to three objects and shifts their values cyclically. section 11.1.1

How Modern C covers it

How deep it goes
Defines syntax, dereferencing, undefined behavior, and aliasing consequences through worked pointer examples.
Examples
Uses double_swap, address-passing calls, pointer dereferences, and a cyclic-shift exercise.
What it assumes
Assumes basic functions and objects, then teaches pointer types, addresses, dereferencing, and aliasing in context.
What you can do after
Apply it via pointer parameters to modify caller-owned objects, while avoiding null, indeterminate, and invalid aliasing cases.
How it connects
Connects pointers, dereferencing, memory state, and aliasing.

Also explained in

Compare how 2 books explain address-of operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.