Workshop: Navigating Data with Pointer Offsets, Explained

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

← Pointer-Based String ProcessingNext lesson: Workshop: Functions with Pointer Parameters →

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

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.

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 Workshop: Navigating Data with Pointer Offsets

How do you get the index from a pointer into a C array?
Subtract the start of the array from the pointer: p - scores gives the index of the element p points to, because pointer subtraction counts elements, not bytes. For example, if a loop leaves best pointing at the fastest time in laps, best - laps is that lap's position. This lets a pointer loop report positions without keeping a separate counter.
How do you filter an array into another array using pointers in C?
Use two pointers: one reads every element of the source, and a writer pointer marks the next free element of the destination. When a value passes the test, write it with *out = *p; and then advance out, but only inside the if. After the loop, out - dest is how many values were kept. Size the destination for the worst case, where every value passes.
How do you reverse an integer array in place with pointers in C?
Set left to the first element and right to the last, a + n - 1, then swap the values they point to and move left forward and right backward while left < right. Six elements take three swaps, five take two, and a middle element never moves. Starting right at a + n is a common bug, because that address is one past the last element.
Why use left < right instead of left != right when reversing an array?
With an even number of elements, the two pointers never land on the same element; they cross. With six elements, after the third swap left is on element 3 and right is on element 2, so left != right is still true and the loop would run off the array. The test left < right stops correctly whether the pointers meet, as with an odd count, or cross.

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 →