C Programming

Lesson 3 of 11

Pointers

A pointer is just a variable that stores a memory address instead of a value. That's it, everything else about pointers is a consequence of that one idea.

C
  • &xp is the address-of operator, "give me the memory address where xp lives".
  • int *xpPtr declares xpPtr as "a pointer to an int".
  • *xpPtr is the dereference operator used on an existing pointer, "go to the address this pointer holds, and give me (or set) the value there".

Why bother?

Without pointers, C functions can only work with copies of the arguments you pass in:

C

Passing a pointer lets a function reach back into the caller's memory and modify it directly, this is how C simulates "pass by reference" since it only ever passes values (and an address is just a value).

WARNING

A pointer that doesn't point at valid memory (never initialized, or freed already) is called a dangling pointer. Dereferencing one is undefined behavior, it might crash, or worse, silently corrupt unrelated memory. Always initialize pointers, even to NULL.

📝 Pointers Quiz

Passing score: 70%
  1. 1.What does the & operator do when applied to a variable?

  2. 2.Passing a pointer to a function lets that function modify the caller's original variable.

  3. 3.Given "int *p = &x;", the ____ operator (*p) reads or writes the value p points to.