🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Lookup Tables with String Pointers
Use arrays of pointers to strings for lookup tables, two-way queries, multi-line input and pointer-swap sorting.
What You Will Learn
- How an array of pointers to strings is laid out in memory
- How to build a safe day-name lookup with range checking
- How to answer person-to-city and city-to-people queries with parallel arrays
- How to read lines into separate heap strings and sort them by swapping pointers
- Why lookup tables are central to embedded C programming
Prerequisites
- Lectures cp9_48 to cp9_52
- Pointers, arrays and malloc/free
- strcmp and fgets
So far every program handled one string. Real firmware handles many: a table of command names, a list of menu entries, a set of device names. In this lecture of our free C programming course you will learn how to use an array of pointers to strings in C to build lookup tables, answer two-way queries and sort names without moving a single character. The exercises from the end of the Strings chapter cover exactly these jobs: printing a day name from a number, finding a city from a person and the people from a city, sorting ten names in descending order, and reading several lines of text into separate strings.
If you understand why an array of pointers is cheaper and more flexible than a two dimensional character array, you understand one of the most important patterns in embedded C programming, because every command table, error-message table and menu in a real device is built this way.
Array of Pointers to Strings: The Memory Picture
An array of pointers holds addresses, one per string. The characters themselves live elsewhere: in read-only memory for literals, or on the heap for strings you create at run time. The array is just an index that lets you reach each string by number.
| Feature | Array of pointers | 2-D char array |
|---|---|---|
| Storage for the index | One pointer per string | None |
| Storage for text | Exactly the length of each string plus a terminator | Every row is as wide as the longest string |
| Reordering strings | Swap two pointers | Copy whole rows |
| Strings can be literals | Yes, as const char * | Copied into the array |
| Can be edited in place | Only if the pointers point at writable memory | Yes |
| Best for | Lookup tables, sorting, variable length text | Fixed-size, editable records |
Lookup Table 1: Day Name From a Number
The exercise says: read a number from 0 to 6 and print the day, with 0 meaning Sunday. The table makes the solution a single indexed read. The interesting part is the guard: a number outside the range must not index the table, because reading past the end of an array is undefined behaviour. We write the lookup as a function that returns NULL for a bad number, so callers decide how to report the problem.
The table is declared static const char *const. Read the declaration from right to left: the array holds constant pointers, and each pointer points at constant characters. Nothing can be modified, so the compiler may place the whole table in flash memory. That is the correct choice on a microcontroller where RAM is scarce.
#include <stdio.h>
static const char *const day_name[7] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
static const char *day_of(int d)
{
return (d >= 0 && d <= 6) ? day_name[d] : NULL;
}
int main(void)
{
const int tests[] = {0, 3, 6, 7, -1};
for (size_t i = 0; i < sizeof tests / sizeof tests[0]; i++) {
const char *name = day_of(tests[i]);
if (name != NULL)
printf("%2d -> %s\n", tests[i], name);
else
printf("%2d -> out of range (use 0 to 6)\n", tests[i]);
}
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o weekday weekday.c
./weekday
0 -> Sunday
3 -> Wednesday
6 -> Saturday
7 -> out of range (use 0 to 6)
-1 -> out of range (use 0 to 6)
The loop tests five values: three valid ones and two invalid ones on either side of the range. Always test just outside the boundaries; that is where lookup bugs hide.
Lookup Table 2: People and Cities, Both Directions
The next exercise stores names in one array and cities in another, then answers two kinds of questions. If the user types a person, print the person’s city. If the user types a city, print everyone who lives there. The key idea is the parallel arrays convention: the person at index i lives in the city at index i. One loop over the index reaches both.
We compare with strcmp, never with ==. Comparing two pointers asks whether they point to the same address, not whether the text is equal, and that is a classic beginner bug. The program reads queries from standard input until end-of-file, which makes it easy to test by piping text.
#include <stdio.h>
#include <string.h>
static const char *const person[] = {
"Asha", "Bharat", "Chitra", "Dev", "Esha", "Farid"
};
static const char *const city[] = {
"Pune", "Hyderabad", "Pune", "Chennai", "Hyderabad", "Pune"
};
#define COUNT (sizeof person / sizeof person[0])
int main(void)
{
char line[48];
while (fgets(line, sizeof line, stdin) != NULL) {
size_t i, hits = 0;
line[strcspn(line, "\n")] = '\0';
for (i = 0; i < COUNT; i++) {
if (strcmp(line, person[i]) == 0) {
printf("%s lives in %s\n", line, city[i]);
hits++;
}
}
if (hits == 0) {
for (i = 0; i < COUNT; i++) {
if (strcmp(line, city[i]) == 0) {
if (hits++ == 0)
printf("%s:", line);
printf(" %s", person[i]);
}
}
if (hits > 0)
putchar('\n');
}
if (hits == 0)
printf("%s: no match\n", line);
}
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o lookup lookup.c
printf 'Dev\nPune\nMumbai\n' | ./lookup
Dev lives in Chennai
Pune: Asha Chitra Farid
Mumbai: no match
The last query shows the third result of a good lookup: a clear no match message rather than silence.
Scaling up. Parallel arrays are fine for small, fixed tables. When each record has many fields, group them in a struct and keep one array of structs, so the fields cannot drift out of step.
Store Several Lines as Separate Strings
The last exercise reads lines of text and keeps each one as its own string, reachable through an array of pointers. A single buffer cannot do this, because the next call to fgets overwrites the previous line. Each line needs its own storage, so we copy it into a freshly allocated block and store the block’s address in the array.
Sorting Names in Descending Order Without Copying Text
Once the lines are in the array, sorting them is a matter of reordering pointers. We use selection sort: for each position, find the pointer whose string compares greatest, and swap it into place. Swapping two pointers moves eight bytes (or four on a 32-bit target) instead of copying a whole name. The comparison is strcmp(a, b) > 0, which means a comes after b alphabetically, so choosing the greatest each time gives descending order.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINES 10
#define LINE_LEN 64
static char *copy_string(const char *s)
{
size_t n = strlen(s) + 1;
char *p = malloc(n);
if (p != NULL)
memcpy(p, s, n);
return p;
}
int main(void)
{
char *name[MAX_LINES];
char buf[LINE_LEN];
size_t count = 0;
while (count < MAX_LINES && fgets(buf, sizeof buf, stdin) != NULL) {
buf[strcspn(buf, "\n")] = '\0';
if (buf[0] == '\0')
continue;
name[count] = copy_string(buf);
if (name[count] == NULL) {
perror("malloc");
break;
}
count++;
}
/* selection sort, descending: only the pointers move */
for (size_t i = 0; i + 1 < count; i++) {
size_t best = i;
for (size_t j = i + 1; j < count; j++)
if (strcmp(name[j], name[best]) > 0)
best = j;
char *tmp = name[i];
name[i] = name[best];
name[best] = tmp;
}
for (size_t i = 0; i < count; i++) {
printf("%zu. %s\n", i + 1, name[i]);
free(name[i]);
}
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o sort_names sort_names.c
printf 'Kiran\nasha\nZoya\nbala\nMohan\nDev\n' | ./sort_names
1. bala
2. asha
3. Zoya
4. Mohan
5. Kiran
6. Dev
Look carefully: bala and asha come first and Dev comes last. That is not a bug. strcmp compares character codes, and every lowercase letter has a larger code than every capital. In descending order, lowercase names therefore come before capitalised ones. If you want a human-friendly order, compare lowercase copies or use a case-insensitive comparison such as strcasecmp where your platform provides it.
Common Mistakes and Troubleshooting
- Using
==to compare strings. It compares addresses. Usestrcmp. - Indexing the table with an unchecked number. Validate the range before you read.
- Using one buffer for every line. All array entries would point at the same bytes, which show only the last line. Allocate separate storage.
- Forgetting
free. On a long-running device every unreleased line is a leak. The program frees each entry after printing. - Not checking
malloc. On small targets allocation can fail; the code stops reading and still frees what it has. - Expecting dictionary order. Plain
strcmporders by character code, not by human alphabet. - Letting parallel arrays drift. Add a compile-time check that both arrays have the same number of entries, or use an array of structs.
Best Practices, Performance and Security
- Make lookup tables
static const; they cost no RAM and cannot be corrupted at run time. - Prefer returning
NULLover printing from deep inside a lookup function; separate lookup from reporting. - Cap the number of lines and the length of each line. The code stops at ten lines and uses
fgetswith the buffer size, so hostile input cannot overflow anything. - For large tables, keep them sorted and use
bsearchwith a comparison function instead of a linear scan. - When you store pointers to heap strings, define who owns them and who frees them. In this program the same function that allocates them frees them.
Practice Challenges
- Turn the people and cities tables into an array of structs and rewrite the lookup.
- Sort the names ignoring case, then print them ascending and descending.
- Build a command table of names and function pointers, then dispatch the typed word. This is the real embedded use of everything in this lecture.
Key Takeaways
- An array of pointers is an index; the text lives elsewhere.
- Declare read-only tables as
static const char *constto save RAM. - Parallel arrays answer queries in both directions; check ranges first.
- Compare strings with
strcmpand reorder by swapping pointers. - Every stored line needs its own storage, and every allocation needs an owner who frees it.
Conclusion
You have now covered the whole pattern: define a table, guard the index, search it, sort it, and manage the memory of the strings it points to. The same few lines scale from a seven-entry day table to a command interpreter with hundreds of entries.
The final lecture of this batch returns to the answer key at the end of the Strings chapter and turns each wrong-answer explanation into a rule you can remember, followed by a quiz and interview questions. Finish it to complete this part of the free C tutorial on embedded C programming.
Frequently Asked Questions
What is an array of pointers to strings in C?
An array whose elements are char * pointers, each pointing to a separate string. It is a compact index to text stored elsewhere.
Why use an array of pointers instead of a 2-D char array?
It wastes no space on short strings, and sorting means swapping pointers instead of copying whole rows.
How do I sort strings stored in an array of pointers?
Compare with strcmp and swap the pointers, not the characters. Selection sort or qsort with a comparison function both work.
Why does my descending sort put lowercase names first?
strcmp compares character codes, and lowercase letters have larger codes than capitals. Compare case-folded copies for a human order.
How do I store several lines read from the user?
Read each line into a temporary buffer, then malloc a block of the right size, copy the text and store the pointer. Free every block when you are done.
Where are these tables used in embedded systems?
Command tables, error message tables and menu systems, all topics in this free embedded C course for embedded C programming.
Keep Going With the Free Embedded C Course
EmbeddedPathashala teaches embedded C programming, Linux kernel development and device drivers for free. Pick the next lecture and keep your streak going.

2 Comments