Search topics...

Show how to declare a pointer to constant data in C. Show how to declare a function pointer in C.

0 upvotes
Practice with AISoon

Pointer to constant data — the pointee is read-only through the pointer, but the pointer itself may be reassigned. Read declarations right-to-left:

c
const int *p; /* p points to a const int: *p is read-only, p can change */
int const *p2; /* identical meaning to the line above */

Contrast with a constant pointer (the pointer is fixed, the data is writable), and a constant pointer to constant data:

c
int x = 5, y = 6;
int * const cp = &x; /* cp is const: cannot repoint, but *cp = 10 is OK */
const int * const cpc = &x; /* neither the pointer nor the pointee may change */
const int *p;
p = &x; /* OK: repointing the pointer is allowed */
/* *p = 7; // ERROR: cannot write through pointer-to-const */
/* *cp = 7; is OK; cp = &y; would be an ERROR */

A very common, correct use is a function parameter promising not to modify the caller's buffer: size_t strlen(const char *s);.

Function pointer — a variable that holds the address of a function with a specific signature. The parentheses around *fp are required, otherwise it parses as a function returning a pointer:

c
int add(int a, int b) { return a + b; }
int (*fp)(int, int); /* fp: pointer to a function taking (int,int) returning int */
fp = &add; /* or simply fp = add; (function name decays to address) */
int r = fp(2, 3); /* call: r == 5; (*fp)(2,3) is equivalent */

A typedef makes function-pointer code far more readable (useful for callback tables / jump tables):

c
typedef int (*binop_t)(int, int);
binop_t op = add;
int r2 = op(4, 5); /* r2 == 9 */