Pointer Arithmetic in C, Explained with Code Examples

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

← Pointer Fundamentals in CNext lesson: Why Array Names Act Like Pointers →

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

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.

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 Pointer Arithmetic in C

What does adding 1 to a pointer do in C?
Adding 1 moves the pointer by one whole item, not one byte. The step is the size of the type it points to, so from address 4000 a char pointer moves to 4001, an int pointer to 4004 when int is 4 bytes, and a double pointer to 4008 when double is 8 bytes. This is why a pointer's type must match what it points at.
What is the difference between *p + 1 and *(p + 1) in C?
*p + 1 reads the value p points to and adds 1 to it, while *(p + 1) reads the value in the next element. The star binds more tightly than the plus sign, so the parentheses change the meaning. If p points to an element holding 33 and the next element holds 44, then *p + 1 is 34 and *(p + 1) is 44.
What does subtracting two pointers return in C?
Subtracting two pointers into the same array gives the number of elements between them, not the number of bytes. The result has type ptrdiff_t from stddef.h, can be negative, and prints with %td. For an array of doubles, pointers to index 1 and index 5 differ by 4, even though they are 32 bytes apart when a double takes 8 bytes. Adding two pointers is not allowed.
Is it safe to point one past the end of an array in C?
A pointer may hold the address just past the last element, but only for comparing; reading or writing there is undefined behavior, and so is moving farther or before the first element. That is why a loop such as for (p = &scores[0]; p < end; p++), with end = &scores[0] + count, stops correctly, while p <= end visits one element too many.

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 →