Nearby lessons
95 of 124C - Array of Pointers
An array of pointers holds addresses instead of values. Learn the int *a[5] declaration, why it is the natural way to store a list of strings, and how it differs from a pointer to an array.
Declaring an Array of Pointers
Read it from the name outwards: a is an array of 5, of pointers to int:
Initialising at Declaration
Supply the addresses in a brace list, exactly like any other array:
The Main Use — A List of Strings
This is where an array of pointers earns its keep. Each string is exactly as long as it needs to be:
Compared with a 2D char Array
A 2D array gives every string the same width, so short strings waste space. An array of pointers does not — but the strings are read-only:
char names[5][20] | char *names[5] | |
|---|---|---|
| Memory used | 100 bytes, fixed | 40 bytes + the literals |
| Wasted space | Yes, for short strings | None |
| Modifiable text | Yes | No, if pointing at literals |
| Reorder the list | Must copy strings | Just swap pointers |
| Contiguous | Yes | No |
Sorting Without Moving Text
A Menu or Lookup Table
A common practical use: a fixed table of labels indexed by a value:
Passing an Array of Pointers to a Function
The parameter becomes a char ** — the same type as main's argv:
Array of Pointers vs Pointer to Array
One asterisk, one pair of parentheses, two entirely different types. The parentheses change everything:
| Declaration | Means | sizeof |
|---|---|---|
int *a[5] | An array of 5 pointers | 40 bytes |
int (*a)[5] | One pointer to an array of 5 ints | 8 bytes |
An Array of Allocated Blocks
Each pointer can own a separately allocated block — a jagged array where every row has its own length:
Common Mistakes
- Forgetting to initialise the pointers —
int *a[5];holds five garbage addresses. - Modifying a string literal —
names[0][0] = 'X'crashes whennames[0]points at a literal. - Confusing
int *a[5]withint (*a)[5]— check for the parentheses. - Using
sizeofto count strings — it counts pointers, not characters. - Freeing the array instead of the blocks — each allocated block needs its own
free. strcpyinto a literal pointer — there is no writable space there.
char *names[] = {"Rahul"}; then strcpy(names[0], "Priya"); compiles cleanly and then segfaults — you are writing into the program's constant data. Declare the array as const char * so the compiler stops you, or use a 2D array when the text must change.- int *a[5] is an array of 5 pointers to int.
- char *names[] is the standard way to hold a list of strings.
- Each string can be a different length — no wasted space.
- Sorting strings means swapping pointers, not copying text.
- int *a[5] and int (*a)[5] are completely different types.