Arrays of Pointers in C, Explained with Code Examples

UPI Study › Courses › Programming in C › Free lessons › Lesson 8.5 Free with a free account

Arrays of Pointers in C

Programming in C · Chapter 8: Pointers, Pointer Arithmetic, and String Manipulation via PointersSection 8.5 · lesson 52 of 787 min · free with a free account

← Why Array Names Act Like PointersNext lesson: Passing Array Addresses to Functions →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Storing ragged lists of strings as arrays of pointers in C.

  • Declare an array of pointers to const char for a list of names
  • Compare the memory use of a 2D char array and an array of pointers
  • Explain why string literals must not be modified
  • Sort a list of strings by swapping pointers instead of copying text

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (976 words). Read along, or search it.

Opening Question

Names of Every Length in One Row

The Starlight Arcade has twenty machines, and every one has a name. Priya wants one list she can loop over: to print a menu, search, and sort. A row of numbers is easy. But names are text, and they come in every length. Pong and Whack-a-Mole Deluxe Edition are not the same size. So how do you fit them in one tidy row?

The Idea

A Row of Boxes Holding Addresses

A pointer is just a value, so pointers can sit in an array like any other value. That's an array of pointers: a row of boxes, each holding the address of something else. Here, each box holds the address of a piece of text. Box two isn't the word Skee-Ball. It's an arrow to where that word starts. The words themselves are string literals: letters between double quotes in your code. C stores each one somewhere in memory, ending with backslash zero, and the quotes give you its address.

Worked Example

Reading the Games Declaration

Read the declaration from the name outward. games is an array of pointers to const char. Empty brackets are fine with a starting list: C counts the items. The const is there because a literal must not be changed. You'll see clang enforce that in a moment. Line six counts the boxes the usual way, the whole row divided by one box. That works because games is declared right here. Inside the loop, games of i is an address. Percent s follows it, and prints letters until it reaches the backslash zero. The last print does two steps at once. Games of two is the address of Skee-Ball, and the zero after it picks that text's first letter. Build and run. Four machines, and the letter S.

Menu Loop

One Loop Replaces Many Lines

The payoff of a pointer list is that one loop replaces many separate lines. To add a machine, you add one name to the list and change nothing else. People count from one, so the menu prints i plus one, and the program converts back with choice minus one to get the real index. Priya also checks scanf's return value, and that the number is in range, before she uses it. A wrong index would read outside the list. Run it, and pick machine three. Index two holds Skee-Ball. Tokens in, have fun.

Quick Check

Two Sets of Brackets Pick a Letter

Quick check. A list of three toys, and one print with two characters, each picked with two sets of brackets. What does it print? Pause and predict. It prints Ry: a capital R and a small y. Toys of two is the third text, Robot. Its letter zero is the R. Toys of zero is Yo-yo. Count from zero: Y, o, hyphen, then y at index three. K would need the first brackets to count from one. They count from zero, like every index in C.

Ragged Versus Rectangle

Fixed-Width Rows Versus Snug Text

You could store names another way: a 2D array of chars, from seven point four, where every row is a fixed-width box. That's a rectangle. An array of pointers is ragged instead. Each text is only as long as it needs to be. The rectangle must be wide enough for the longest name, so every short name pays for empty space. The pointer table pays one address per name, and stores the text snugly.

Measuring Memory

Which Layout Uses Less Space

Which uses less memory? Measure it, with names of very different lengths. grid has four rows of twenty-eight chars. ptrs holds four addresses. The loop adds up the text the pointers point at, plus one for each backslash zero. Build and run. The rectangle takes one hundred twelve bytes. The pointers take thirty-two for the boxes, plus fifty-one of text: eighty-three. So the pointer table wins here. With names of nearly equal length, the rectangle can win. These sizes are for this Mac.

Read-Only Literals

Const Char Star Protects the Text

There's a second difference, and it matters. Each row of a 2D array is your own copy of the letters, so you may change them. A pointer to a string literal points at text C stored for you, and that text must not be changed. Try to change the first letter of Pinball. Because the pointers are const char star, clang stops you: read-only variable is not assignable. Leave off const and change a letter anyway, and it can compile with no warning at all. But changing a literal is undefined behavior, so this never runs here. Use const char star for literals, and a char array for text you edit.

Sorting Pointers

Swapping Addresses, Not Letters

Last, sorting. With a 2D array, every swap copies whole names around. With an array of pointers, you swap two addresses instead. This is a bubble sort, like seven point eight, comparing names with strcmp from seven point six. When two names are out of order, three lines trade the two addresses, using temp. The letters themselves never move. Build and run. Air Hockey, Claw Crane, Pinball, Skee-Ball: alphabetical.

Memory Picture

The Arrows Moved, the Strings Did Not

Here's what happened in memory. Before the sort, box zero pointed at Skee-Ball. After it, box zero points at Air Hockey. Sorting changed where the arrows point. The strings were never touched, and that's why it's fast.

Quick Check

Sizeof Counts Boxes, Not Text

Quick check. Three short names, stored both ways: a rectangle ten chars wide, and a table of three pointers. On this Mac, what does it print? Pause and predict. It prints 30 24. The rectangle is three rows of ten chars, thirty bytes, however short the names are. The pointer table is three addresses of eight bytes each: twenty-four. sizeof counts only the boxes, not the text they point at. Sixteen would be the letters plus their backslash zeros. That's the text, which lives outside the table.

Key Takeaways

Pointer Tables for Ragged Text

To recap. An array of pointers is a row of boxes, each holding an address, like const char star games. One loop over the list prints a menu, and adding a name changes nothing else. Ragged text saves the empty space a rectangle wastes, but literals are read-only. And sorting a pointer table swaps addresses, never letters.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Arrays of Pointers in C

What is an array of pointers in C?
An array of pointers is an array whose elements are addresses. A common use is a list of strings: const char *games[] = {"Pong", "Pinball", "Skee-Ball"}; stores one address per name, each pointing to where that text starts. games[i] is an address that %s follows to print the name, and games[2][0] is the first letter of the third name, S.
What is the difference between a 2D char array and an array of char pointers in C?
A 2D char array is a rectangle: every row has the same fixed width, wide enough for the longest name, and each row is your own copy that you may change. An array of pointers is ragged: it stores one address per name, and each string takes only its letters plus the null terminator. That often saves memory, but string literals reached through the pointers are read-only.
Why should pointers to string literals be declared const char * in C?
Changing a string literal is undefined behavior, and const makes the compiler enforce that rule. With const char *games[], a line like games[0][0] = 'p'; fails with a read-only variable is not assignable error. Without const, the same line may compile with no warning and then misbehave when it runs. Use const char * for literals and a char array for text you plan to edit.
How do you sort an array of strings in C without copying the text?
Store the strings as an array of pointers and sort the pointers. Compare two names with strcmp, and when they are out of order, swap the two addresses through a temporary pointer: temp = names[j]; names[j] = names[j+1]; names[j+1] = temp;. The letters never move, so each swap costs three pointer assignments instead of copying whole names, as a 2D char array would require.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →