UPI Study › Courses › Programming in C › Free lessons › Lesson 9.2 Free with a free account
Workshop: Navigating Data with Pointer Offsets
Programming in C · Chapter 9: String Manipulation via Pointers, File Streams, and File HandlingSection 9.2 · lesson 55 of 786 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: Workshop: Functions with Pointer Parameters →← Pointer-Based String ProcessingNext lesson: Workshop: Functions with Pointer Parameters →
In this lesson
Summing, filtering, and reversing arrays with pointers instead of indexes.
- Loop over an array with a pointer and an end pointer
- Convert a pointer back to an index with pointer subtraction
- Filter values into a new array with a separate writer pointer
- Reverse an array in place with two pointers moving inward
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 (929 words). Read along, or search it.
Opening Question
Can a Pointer Replace the Index
Every array loop you've written so far counted with an index: i is zero, then one, then two. Now put the index away. Can a pointer alone add up a score board, pick out the good scores, and flip the board around? It can. The arcade's data doesn't change. Only the way you reach it does.
Sum and Best
An End Pointer Computed Once
Priya has six scores from the Starlight Arcade board. She wants their sum, their average, and the best score. First, end. Scores plus n is the address just after the last box. Compute it once, before the loop. Then p starts at box zero. Each pass adds star p to the sum, checks it against the best so far, and moves p one box right. The loop runs while p is less than end. Comparing with end is fine. Reading through it is not: no box lives there.
Tracing the Loop
Following the First Passes
Follow the first passes. On box zero, the sum becomes seventy-two. p steps to box one. Now the sum is one hundred sixty-seven, and ninety-five is the new best. On box two, forty-eight joins the sum, and so on, until p reaches end with a total of four hundred forty-three. Build and run. Sum 443, max 95, and an average of about 73.8.
Index Versus Pointer
Same Visits, a Different Kind of Position
With an index, you'd start i at zero, test i less than n, read scores of i, and step with i plus plus. The pointer loop makes the same visits. It keeps the position as an address, not a counter. Star p plays the part of scores of i. And to get the position number back, subtract. p minus scores is the index of the box p touches.
Quick Check
A Tie Does Not Beat the Best
Quick check. Sam times five laps on the racing game, in seconds. This loop keeps a pointer to the fastest lap. Then it prints that lap, and best minus laps. What does it print? Pause and predict. It prints 28 at 1. The test is strictly less than. The second 28 ties the best, but doesn't beat it, so best stays on box one. Then best minus laps turns that pointer back into an index: one. 28 at 3 would need less than or equal, which moves to every tie.
Filtering
A Writer Pointer Moves Only on Keep
The arcade also has a high scorers board, with only the scores above seventy. That takes two pointers at once. One pointer, p, reads every score in the source row. A second pointer, out, marks the next free box in the new row. out moves only when a score is kept. Write the score where out points, then step out forward. At the end, out minus dest is how many were kept: the boxes between the two. The source comes in as const int star, because the function only reads it. And high has six boxes: room for the worst case, all six passing. Build and run. Four scores above seventy: 72, 95, 88, and 79.
Common Mistake
Moving the Writer on Every Pass
A common slip is to move out on every pass, not just inside the if. Here's what that does. Move out plus plus below the if's closing brace. Now the writer steps forward even when a score is skipped. Build and run. Six scores, and two of them are zeros: holes, where the skipped scores left their boxes empty. high started filled with zeros, so the holes show as zero. Without that, they'd hold leftover junk. Move the writer only inside the if.
Reversing
Swapping From Both Ends Inward
Last, the arcade wants the board shown from the last game to the first. No second array is needed. left points at the first box. right points at the last box: a plus n minus one. Swap the two numbers they touch. Then left moves one box right, and right moves one box left. Repeat while left is less than right. When they meet or cross, everything has been swapped. A small show function prints the row with the same pointer walk. Build and run: the board, then the same board backward. Six boxes took three swaps.
Loop Test
Why Less Than Beats Not Equal
Why less than, and not not-equal? With six boxes, the two pointers never touch the same box. After the third swap, left is on box three and right is on box two. They've crossed. Not-equal would still be true, and the loop would run off the row.
Story Resolved
One Box Too Far on the Right
At the arcade, Priya reversed the board, and Sam saw a strange number at the front. She had written right equals a plus n: one box too far. The first swap pulled in a box from outside the row. Sam suggested a check she now uses on every loop: say out loud the first and last box it touches. For six scores, the last is a plus n minus one.
Quick Check
Reversing Five Numbers
Quick check. The same two-pointer reverse now counts its swaps, and it runs on five numbers instead of six. Afterward, it prints the swap count, then the middle box. What does it print? Pause and predict. It prints 2 swaps, 30. The first swap trades ten and fifty. The second trades twenty and forty. Then left and right both sit on box two. left less than right is false, so the loop stops, and thirty, in the middle, never moves. Three would be right for six numbers. With five, the pointers meet on the middle box before a third swap.
Key Takeaways
End Pointers, Writers, and Two Ends
To recap. Loop while p is less than end, and never read through end. p minus the start of the array gives the index. To filter, the writer pointer moves only when a value is kept. And to reverse in place, swap from both ends while left is less than right.
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 Workshop: Navigating Data with Pointer Offsets
How do you get the index from a pointer into a C array?
How do you filter an array into another array using pointers in C?
How do you reverse an integer array in place with pointers in C?
Why use left < right instead of left != right when reversing an array?
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 →