An array of pointers holds addresses. The most common case is an array of strings: const char *names[] = {"Ann", "Bob"}. Each element points to a separate string, so rearranging the array only moves pointers, not text. argv in main is an array of pointers.
Remember
const char *names[] = {"Ann", "Bob", "Cy"};
names[1] /* "Bob" (a pointer) */
names[1][0] /* 'B' */
int *rows[3]; /* three int pointers */
Reference
Cheat Sheet
Keep these facts handy while you work with Array of Pointers in C.
Topic
Detail
Declare
type *name[count];
Element
Each is a pointer
Strings
Array of const char *
Compare
int (*p)[3] is a pointer to an array
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Pointer to Pointer.
Example 1 — A table of strings
Print each name and its length.
C
#include <stdio.h>
#include <string.h>
int main(void) {
const char *names[] = {"Ann", "Bob", "Cy"};
int n = sizeof names / sizeof names[0];
for (int i = 0; i < n; i++) {
printf("%d: %s (%zu)\n", i, names[i], strlen(names[i]));
}
return 0;
}
Output
0: Ann (3)
1: Bob (3)
2: Cy (2)
How It Works
names holds three pointers to string literals.
sizeof names / sizeof names[0] counts pointers, not characters.
Each names[i] can be passed to string functions.
Edge Cases & Pitfalls
Check these before relying on Array of Pointers in real programs.
2d
Not a 2D char array
Strings in an array of pointers can have different lengths and may be read-only literals.
prec
Precedence in declarations
int *a[3] is an array of pointers; int (*a)[3] is a pointer to an array.
Remember
Key Takeaways
Elements: pointers, not values.
Strings: a natural fit.
Sorting: swap pointers, not text.
One line: An array of pointers holds addresses.
Frequently Asked Questions
A 2D array is one contiguous block of rows with equal length. An array of pointers holds separate addresses whose targets may be scattered and of different lengths.
argv is an array of char pointers holding the command-line arguments. argv[0] is usually the program name.
Continue with "C Pointer to Pointer" next. Use double pointers to change a pointer from inside a function. The C Pointers hub lists every topic in order.