UPI Study › Courses › Programming in C › Free lessons › Lesson 8.3 Free with a free account
Pointer Arithmetic in C
Programming in C · Chapter 8: Pointers, Pointer Arithmetic, and String Manipulation via PointersSection 8.3 · lesson 50 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: Why Array Names Act Like Pointers →← Pointer Fundamentals in CNext lesson: Why Array Names Act Like Pointers →
In this lesson
How C pointers step, walk arrays, subtract, and stay in bounds.
- Explain why adding 1 to a pointer moves it by the size of its type
- Walk an array with a pointer and an end pointer instead of an index
- Subtract two pointers into the same array to count the items between them
- Distinguish *p + 1 from *(p + 1)
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 (962 words). Read along, or search it.
Opening Question
What Should P Plus One Be
Say an int pointer, p, holds the address 4000. What should p plus one be? 4001 sounds right. But an int takes four bytes here, so 4001 would land in the middle of the number. C does something smarter. It adds the size of the thing the pointer points at. The pointer's type sets the step.
Step Size
The Pointer's Type Sets the Step
Here's the same street of mailboxes, with three kinds of pointer. A char takes one byte, an int four, and a double eight, on this Mac. So from 4000, a char pointer steps to 4001, an int pointer to 4004, and a double pointer to 4008. You write the same p plus one every time. The type chooses the step. That's why a pointer's type must match what it points at. Watch the parentheses too. Star p plus one is the value, plus one. Star of p plus one, in parentheses, is the value in the next box.
Proof in Code
Measuring the Bytes Between Addresses
Seeing beats believing, so here's a real run. Three little arrays, and a pointer to the first box of each. To count the bytes between two addresses, cast each pointer to char star first. A char is exactly one byte, so the subtraction counts bytes. The result is printed with percent t d, the format for the difference of two pointers. Build and run. One, four and eight bytes, just like the picture.
Walking an Array
A Pointer, an End Pointer, No Index
Now the payoff. An array is a row of same-type boxes, side by side. So a pointer that starts at the first box, and steps with p plus plus, visits every box in turn. Priya adds up five game scores this way. p starts at ampersand scores of zero. A second pointer, end, is p plus five: the address just after the last box. The loop keeps going while p is less than end. Comparing two pointers like that is fine when both point into the same array. Inside, star p is the score under the pointer, so the program never writes an index. Build and run. Five scores, one per pass, and a total of eleven seventy-five. Build end once, before the loop, from the count. Then p less than end is the whole stopping rule, like i less than count in a loop with an index.
Quick Check
One Star Outside, One Star Inside
Quick check. A pointer starts at the first of four lap times, then jumps ahead by two. The print line has one star outside the parentheses, and one inside. What does it print? Pause and predict. It prints 34 44. p plus two moves two whole ints, from box zero to box two, which holds thirty-three. Star p plus one reads thirty-three, then adds one: thirty-four. Star of p plus one steps to box three first: forty-four. Twenty-three, thirty-three would need p to sit at box one, but p equals p plus two moved it to box two.
Pointer Subtraction
Counting Items Between Two Pointers
Two pointers into the same array can also be subtracted. The answer isn't a number of bytes. It's how many items lie between them. So if third points two boxes after first, third minus first is two. The result has its own type, p t r diff underscore t, from stddef dot h. It can be negative, and it's printed with percent t d. You can compare such pointers with less than, greater than, equals, and not equals. But adding two pointers has no meaning, and C won't allow it.
Worked Example
Turning a Pointer Back Into an Index
This program uses subtraction to turn a pointer back into an index. It hunts for the highest score, and remembers where it was with a pointer called best. Then best minus first says how far best is from the start. Build and run. The best score, four ten, sits at index three. Third minus first is two, and first minus third is minus two. first less than third is one, meaning true. And the last line shows the parentheses trap with real numbers: one twenty one, then three forty. Now add one line that tries first plus third. Build again, and clang refuses: invalid operands to binary expression.
Bounds Rule
One Past the End Is Only for Comparing
A pointer can safely visit every box of the array. It may also hold the address just past the last box, like end, as long as you only compare it. You must not read or write there. And if a pointer moves even farther, or before the first box, the program has undefined behavior. The C rules then promise nothing: it may crash, show nonsense, or seem to work today and break tomorrow. So there's no printout to show here.
Common Mistake
Less Than or Equal Visits Too Many
Back at the arcade, Sam reviewed Priya's score loop and spotted p less than or equal to end. That visits one box too many, he said. The sixth box isn't ours. Priya fixed the one character. No test run was needed. Reading the loop against the picture was enough. Know the count, build end from it, and stop with p less than end.
Quick Check
Items, Not Bytes, Between Two Doubles
Quick check. Six prices, as doubles, which take eight bytes each on this Mac. a points at box one, and b at box five. What does b minus a print? Pause and predict. It prints 4. Subtracting pointers counts items, not bytes. From box one to box five is four doubles. Thirty-two is the number of bytes between them, which is what you'd get after casting both to char star. And it's b minus a, so the answer is positive.
Key Takeaways
Steps, Walks, and Differences
To recap. p plus one moves by one whole item: the pointer's type sets the step. p plus plus, with an end pointer and p less than end, walks a whole array without an index. Subtracting two pointers into one array counts the items between them, as a p t r diff underscore t. And never read or write past the end. One past is only for comparing.
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 Pointer Arithmetic in C
What does adding 1 to a pointer do in C?
What is the difference between *p + 1 and *(p + 1) in C?
What does subtracting two pointers return in C?
Is it safe to point one past the end of an array in C?
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 →