LOGBOOK

HELP

← again tap: answer good → ↑ swipe up at the end: next

1 / 11
Other keys: show • Space: good • 1-4: rate • 0: skip • 5: flag

Question

How do pointers work in C conditions and what is NULL?

Answer

A pointer is just a memory address, so in a condition NULL (which is 0) is false and any real address is true — that's why if (a) tests "is this pointer set?".

void foo(int *a, int *b) {
    int c;

    // These three are equivalent:
    if (a != NULL) c = *a;
    if (a != 0)    c = *a;
    // Most idiomatic
    if (a)         c = *a;
}

NULL is defined as 0:

// Common definition
#define NULL ((void*)0)

// Pointer to nothing
int *p = NULL;
if (p) {
    // This won't execute - p is NULL (zero)
}

The ternary operator ?::

// Instead of:
if (a != NULL) c = *a;
else c = 0;

// Write:
c = a ? *a : 0;

Avoid nested ternary:

// Hard to read!
c = a ? *a : b ? *b : 0;
or press any other key

Question

What is a pointer and how do & and * work?

Answer

A pointer is a variable whose value is a memory address; &x produces the address of x, and *p follows a pointer to read or write what it points at.

Address-of and dereference

* &a yields a's address (16); store it in ap and *ap reads or writes a's value (5). *

int a = 5, b = 7, c;
// ap holds the ADDRESS of a
int *ap = &a;

Memory visualization:

Variable:  a    b    c    ap
Address:  16   20   24   28
Value:     5    7    ?   16  ← ap contains address of a
                         ↓
                    points to a

The operators:

  • &a → "address of a" → returns 16 (where a lives)
  • *ap → "value at address in ap" → returns 5 (contents of a)
// Changes a to 10 (through the pointer)
*ap = 10;
// Now ap points to b
ap = &b;
// Changes b to 20
*ap = 20;

Pointer to pointer:

// app points to ap, which points to an int
int **app = ≈
// Changes the int that ap points to
**app = 30;

Tip: Visualize with https://pythontutor.com/c.html - it shows pointers as arrows!

Go deeper:

or press any other key