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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Passing Array Addresses to Functions →← Why Array Names Act Like PointersNext lesson: Passing Array Addresses to Functions →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is the difference between a 2D char array and an array of char pointers in C?
Why should pointers to string literals be declared const char * in C?
How do you sort an array of strings in C without copying the text?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →