🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Array of Pointers to Strings
Free C programming course: store only the addresses of strings, compare the memory cost with a 2-D char array, then test yourself with a quiz and interview questions.
An array of pointers to strings keeps one pointer per string instead of one fixed-width row. Each pointer holds the address of the first character of a string that lives somewhere else. In this lecture of our free C programming course you will declare one, see how it sits in memory, compare its size with the 2-D table from the earlier lectures, and decide which is better for embedded C programming. At the end you will find a quiz and interview questions covering the whole group of lectures.
What You Will Learn
- How to declare and initialize an array of pointers to strings
- How the pointers and the string data are arranged in memory
- How to compute the memory cost and compare it with a 2-D char array
- When each representation wins, using real numbers
- How to loop over the table with an index or a pointer
- How to use such a table for a command lookup
Prerequisites
You need the earlier lectures of this chapter (the 2-D string table, padding, assignment and sorting) and the basics of pointers from the pointers chapter, especially that a pointer holds an address and that a string literal is an array of characters ending in NUL.
Declaring an Array of Pointers to Strings
const char *periph[] = { "UART", "I2C", "SPI", "GPIO", "TIMER" };
Read the declaration from the name outward: periph is an array whose elements are pointers to const char. The size is left empty, so the compiler counts the five initializers. Each initializer is a string literal, which the compiler stores in read-only memory, and the pointer receives the address of its first character.
Two things differ from the 2-D table. There is no LEN, so no padding. And the strings are not copied into the array; the array only refers to them.
| Element | Holds | Points to |
|---|---|---|
| periph[0] | address of first character | U A R T \0 (5 bytes) |
| periph[1] | address of first character | I 2 C \0 (4 bytes) |
| periph[2] | address of first character | S P I \0 (4 bytes) |
| periph[3] | address of first character | G P I O \0 (5 bytes) |
| periph[4] | address of first character | T I M E R \0 (6 bytes) |
The string literals need not be next to each other, and their order in memory is up to the compiler. Only the pointer array gives them an order that your program can rely on.
Memory Cost: Pointers Versus a 2-D Array
A well-known claim says an array of pointers always saves memory. Measure it instead of believing it. Save this as ptrcost.c:
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *periph[] = { "UART", "I2C", "SPI", "GPIO", "TIMER" };
size_t n = sizeof periph / sizeof periph[0];
size_t chars = 0;
for (size_t i = 0; i < n; i++) {
printf("periph[%zu] -> %-6s len %zu\n", i, periph[i], strlen(periph[i]));
chars += strlen(periph[i]) + 1;
}
printf("elements = %zu\n", n);
printf("sizeof(pointer) = %zu\n", sizeof periph[0]);
printf("pointer array = %zu bytes\n", sizeof periph);
printf("string bytes = %zu\n", chars);
printf("total = %zu\n", sizeof periph + chars);
printf("2-D (LEN 8) = %zu\n", n * 8);
printf("2-D (LEN 32) = %zu\n", n * 32);
return 0;
}
gcc -std=c17 -Wall -Wextra -o ptrcost ptrcost.c
./ptrcost
periph[0] -> UART len 4
periph[1] -> I2C len 3
periph[2] -> SPI len 3
periph[3] -> GPIO len 4
periph[4] -> TIMER len 5
elements = 5
sizeof(pointer) = 8
pointer array = 40 bytes
string bytes = 24
total = 64
2-D (LEN 8) = 40
2-D (LEN 32) = 160
On this 64-bit machine, where a pointer is 8 bytes, the pointer version costs 64 bytes and the tight 2-D table with LEN of 8 costs only 40. The pointers themselves eat the saving. The balance flips when rows must be wide, for example LEN of 32, where the 2-D table needs 160 bytes.
| Case (5 strings, 24 text bytes) | 2-D char array | Array of pointers |
|---|---|---|
| 64-bit host, LEN 8 | 40 bytes | 40 + 24 = 64 bytes |
| 64-bit host, LEN 32 | 160 bytes | 64 bytes |
| 32-bit MCU (4-byte pointers), LEN 8 | 40 bytes | 20 + 24 = 44 bytes |
| 32-bit MCU (4-byte pointers), LEN 32 | 160 bytes | 20 + 24 = 44 bytes |
The rule of thumb: the pointer table wins when strings differ a lot in length or when one long entry would force a huge LEN. The 2-D table wins when all strings are short and similar, since it pays no pointer overhead.
The embedded advantage: flash instead of RAM
If you write const char *const periph[] = {...}, both the pointers and the strings are constant, so a typical toolchain can place them entirely in flash. A non-const 2-D table, by contrast, is usually copied into RAM at startup. On a small microcontroller, keeping text out of RAM is often the real reason to choose pointers. Confirm with your linker map, because placement depends on the toolchain.
Walking Through the Table
An index works exactly as with the 2-D array, and periph[i] is a const char * that you can pass to printf or strcmp. You can also step a pointer-to-pointer along the array. Save as walk.c:
#include <stdio.h>
int main(void)
{
const char *const periph[] = { "UART", "I2C", "SPI", "GPIO", "TIMER" };
const size_t n = sizeof periph / sizeof periph[0];
for (const char *const *p = periph; p < periph + n; p++)
printf("slot %td holds \"%s\", first char '%c'\n", p - periph, *p, **p);
printf("periph[3][1] = %c\n", periph[3][1]);
return 0;
}
slot 0 holds "UART", first char 'U'
slot 1 holds "I2C", first char 'I'
slot 2 holds "SPI", first char 'S'
slot 3 holds "GPIO", first char 'G'
slot 4 holds "TIMER", first char 'T'
periph[3][1] = P
Here p points at an array slot, *p is the string pointer stored there, and **p is the first character. Also notice that periph[3][1] uses the same double-subscript syntax as the 2-D array, even though the memory behind it is completely different.
Real Use: A Command Lookup Table
A serial console maps each typed word to a number. Save as lookup.c:
#include <stdio.h>
#include <string.h>
static const char *const cmds[] = { "start", "stop", "reset", "status" };
#define NCMDS (sizeof cmds / sizeof cmds[0])
static int find_cmd(const char *word)
{
for (size_t i = 0; i < NCMDS; i++)
if (strcmp(cmds[i], word) == 0)
return (int)i;
return -1;
}
int main(void)
{
const char *input[] = { "reset", "status", "halt", "start" };
for (size_t i = 0; i < sizeof input / sizeof input[0]; i++)
printf("%-7s -> %d\n", input[i], find_cmd(input[i]));
return 0;
}
reset -> 2
status -> 3
halt -> -1
start -> 0
The returned index can be used to select a handler from a table of function pointers, a pattern you will reach later in the course.
sizeof on a pointer parameter and expecting the array size; forgetting const so the compiler cannot protect the literals; and assuming that two identical literals share one address or that literals sit next to each other.
Best Practices
- Declare tables as
const char *constwhenever the text never changes. - Compute the count with
sizeof table / sizeof table[0]at the place the array is defined. - Choose pointers for uneven lengths and flash-resident text; choose a tight 2-D array when you must modify text in place.
- Compare with
strcmp, never with==on pointers.
Performance and security notes
Looking up a pointer is one extra memory read compared with a 2-D row, which is negligible. Swapping two entries now exchanges two addresses, so sorting costs a fixed few bytes per swap regardless of string length. Security-wise, a pointer array of non-const type tempts you to write into literals; making it const turns that mistake into a compile error.
Summary and Key Takeaways
- An array of pointers to strings stores addresses, not characters.
- Cost is the pointer array plus the packed strings, so pointer size matters.
- It saves memory when lengths vary or LEN would be large, but not always.
const char *consttables can stay in flash on microcontrollers.- Subscript syntax
t[i][j]looks the same as for a 2-D array.
Conclusion
You have now seen both ways to build a table of text in C and, more importantly, how to choose between them with numbers instead of slogans. These ideas feed directly into command parsers, menu systems and logging code in embedded C programming. Use the quiz and interview questions below to lock the chapter in before moving on.
Quiz: Test Yourself
Try each question first, then open the answer.
Q1. How many bytes does char t[6][10]; occupy?
Show answer
60 bytes, since 6 times 10, independent of string content.
Q2. What is the longest string that fits in a row of char t[4][12]?
Show answer
11 characters, because one byte is reserved for the NUL.
Q3. Is t[1] = "red"; valid for a 2-D char array t?
Show answer
No. t[1] is an array and cannot be assigned. Use strcpy or snprintf.
Q4. What does t[2][0] mean for a 2-D string table?
Show answer
The first character of the third string.
Q5. Rows of char t[3][8] hold “ab”, “abcd” and “a”. How many padding bytes are there in total?
Show answer
24 reserved minus (3 + 5 + 2) used equals 14 padding bytes.
Q6. What does strcmp("B", "a") return in ASCII: negative, zero or positive?
Show answer
Negative, because uppercase B (66) is smaller than lowercase a (97).
Q7. How many swaps at most does selection sort need for N strings?
Show answer
N minus 1.
Q8. On a 32-bit MCU, how many bytes does the pointer array of const char *p[] = {"on","off","auto"}; occupy, not counting the text?
Show answer
12 bytes, three pointers of 4 bytes each.
Q9. Which is usually better for text that never changes on a small MCU, and why?
Show answer
A const pointer table, because the data can remain in flash and avoids a RAM copy.
Q10. Why is if (names[i] == "UART") wrong for comparing strings?
Show answer
It compares addresses, not contents. Use strcmp(names[i], “UART”) == 0.
Interview Questions on Strings and Tables
1. How is a two-dimensional character array laid out in memory?
In row-major order: all of row 0, then row 1, and so on, contiguously. Row i begins at offset i times the row width.
2. What is the difference between char a[5][10] and char *a[5]?
The first reserves 50 bytes of characters. The second reserves five pointers that must be made to point at strings elsewhere; no character storage is included.
3. Why can you not assign to an array in C, but can initialize it?
Initialization is performed by the compiler at the declaration. Assignment would require copying a whole array object, which the language does not define; you copy elements with library functions.
4. What is the difference between sizeof and strlen on a string row?
sizeof is the number of bytes reserved for the row; strlen counts characters before the NUL at run time.
5. How would you sort a list of strings cheaply?
Sort an array of pointers, so each swap exchanges two addresses instead of copying entire rows.
6. Is it safe to modify a string literal through a char pointer?
No. It is undefined behavior and often crashes, because literals are normally stored in read-only memory. Copy it into an array first.
7. Why does strncpy not always terminate the destination?
If the source length reaches the limit, it copies exactly that many bytes without adding a NUL, so you must terminate manually.
8. When would you choose a 2-D char array over an array of pointers in firmware?
When strings must be edited in place, when they are short and uniform, or when you want the text and its storage together in one RAM block.
9. How do you stop a string table from being placed in RAM?
Declare it const, for pointer tables const char *const, so the toolchain can keep it in flash; verify with the map file.
Frequently Asked Questions
What is an array of pointers to strings in C?
An array whose elements are char pointers, each holding the address of one string.
Does an array of pointers always use less memory?
No. You pay for the pointers as well as the strings, so on a 64-bit machine with short strings a tight 2-D array can be smaller.
Why is const important for a string pointer table?
It protects the literals from accidental writes and lets the toolchain place the table in flash.
How do I get the number of strings in the table?
Divide sizeof of the array by sizeof of one element, in the scope where the array is defined.
Can I use arr[i][j] with an array of pointers?
Yes. arr[i] is a pointer to a string and the second subscript selects a character in it.
Is this useful for embedded C programming?
Very. Command tables, menus and log messages in firmware are commonly built this way.
Continue Your Free Embedded C Course
You finished this group of lectures. Keep going with the next part of our free C programming course and keep practicing embedded C every day.

2 Comments