Memory & Pointers

a function pointer

Functions live in memory too — their machine code sits at an address, just like data does. A function pointer is a pointer that holds the address of a function, so you can store a function in a variable, pass it as an argument, and call whichever function the pointer currently names. It turns 'which code runs here' into a value you can choose at run time.

A function pointer's type spells out the function's signature: what arguments it takes and what it returns, because that is what you need to call it correctly. You set it by naming a function (the name decays to its address, much like an array name), and you call through it by writing the pointer followed by arguments. The most common use is a callback: you hand a function pointer to some general routine and it calls back into your code at the right moment — for example qsort() takes a comparison function and calls it to decide the order of two elements, so the same sort works for ints, strings, or structs depending on the function you pass. Tables of function pointers also implement simple dispatch, picking an action by index.

The honest caveat is that the declaration syntax is famously ugly — the parentheses and stars cluster awkwardly — and most real code hides it behind a typedef so the rest reads cleanly. And a function pointer is still a pointer: calling through one that is null or stale is undefined behaviour, so the same 'check before you trust it' discipline applies.

int add(int a, int b) { return a + b; } int (*op)(int, int) = add; int r = op(2, 3); — op holds add's address; calling op(2, 3) runs add and r is 5. Assign op = sub later and the same call now subtracts.

int (*op)(int, int) names a function; op(2,3) calls whatever it points at.

A function pointer points into the program's read-only code segment, not at data, so it is a different beast from an object pointer — mixing the two or doing pointer arithmetic on a function pointer is not meaningful. Wrap the declaration in a typedef in real code; the bare syntax is error-prone to read.

Also called
pointer to functioncallback pointer指向函式的指標