UPI Study › Courses › C++ Programming › Free lessons › Lesson 10.5 Free with a free account
Pointers
C++ Programming · Chapter 10: File Access and MemorySection 10.5 · lesson 73 of 84video coming soon
← Applied Challenge: File Operation ExercisesNext lesson: The Memory Landscape →
In this lesson
Variables that hold addresses.
- Take an address, store it, and dereference it
- Use nullptr; predict pointer arithmetic by type
- Explain array decay and the arrow operator
- Choose const forms, and pointer or reference parameters
Transcript
Everything said in the video, section by section (1,807 words). Read along, or search it.
Opening Idea
A Pointer Is a Variable Holding a Number
Every variable sits somewhere, and that somewhere has a number. A pointer is an ordinary variable whose value happens to be one of those numbers. That single idea explains several things you've been asked to take on trust. Why an array isn't copied into a function, why its length doesn't travel with it, and what a reference parameter is really doing. This section closes those promises.
Addresses
Where a Variable Lives in Memory
Memory is a very long row of numbered slots. When you declare a variable, a run of consecutive slots is set aside for it, and the number of the first one is that variable's address. The ampersand operator, placed in front of a variable, produces it. Printing count gives forty-two: its value. Printing ampersand count gives a large hexadecimal number: where it lives. With four-byte ints, count might sit at address one thousand, and total at one thousand four. The value and the place are two different things, and both can be held in a variable. The last line prints one, for true: total lives at a different address.
Dereferencing
Reading and Writing Through a Pointer
Int star p declares a variable that holds the address of an int. Here, it's set to the address of count. Comparing p with ampersand count prints one: true. Printing star p gives the value living there, forty-two. The star in front of a pointer means the thing at that address, and it works in both directions. You can read through it, or assign through it to change the original variable. Changing star p changes count, because they're the same storage. And a pointer is itself a variable, so it has an address of its own, here different from count's.
Common Confusion
Two Roles for the Star Symbol
The same star symbol plays two roles, so read the context, not the character. In int star p, it's a declaration: create a variable holding the address of an int. In star p equals seven, it's a dereference: store seven where p points, so count becomes seven. Reading star p into a new variable is also a dereference. And p equals ampersand total uses no star at all. It points p somewhere else, and count is untouched. Run it: count and x are seven, and star p now reads total, nine.
Pointer Types
Why the Type Sets Width and Step
The type isn't decoration. Int star tells the compiler two things it couldn't otherwise work out: how many slots to read, and how far one step forward goes. A double star holding the same number would read eight slots instead of four. Here, star ip is four bytes wide, and star dp is eight.
Pointer States
Rubbish, Null, and Valid Pointers
A pointer declared without a value holds whatever was already in its storage, almost certainly not the address of anything you own. Following it is undefined behavior. The usual outcome is the program stopping abruptly, though it may do something worse, and quieter. So there are three states. A holds rubbish: never follow it. B is set to nullptr: it deliberately points at nothing, and can be tested. C points at a real variable. An uninitialized pointer and a null pointer aren't the same. The first holds an arbitrary number that can't be distinguished from a valid one. There's no test you can write. The second holds a value reserved to mean points at nothing. It can be tested, and following it usually fails immediately and obviously, rather than corrupting something. So give every pointer a value at the point of declaration, using nullptr when you have nothing to point at yet.
Pointer Arithmetic
Adding One Moves a Whole Item
Adding one to a pointer doesn't add one to the address. It moves forward by one whole item of the type pointed at. A char pointer at one thousand, plus one, is one thousand one. An int pointer plus one is one thousand four. A double pointer plus one is one thousand eight. Plus three moves three whole items: twelve bytes for ints, and twenty-four for doubles.
Measured Gaps
Byte Distances and Array Bounds
Here is the real byte gap, measured by the compiler's own arithmetic. Plus one is one, four and eight bytes away. Plus three is three, twelve and twenty-four. That's exactly what you want when stepping through consecutive items. But it's only defined while the pointer stays within a single array, or one position past its last item, so loops can test for the end. Anything else gives a result the language makes no promises about, and nothing checks it.
Array Decay
Array Names Become First-Item Pointers
Here's the explanation held over from passing arrays to functions. In almost every context, an array's name converts automatically to a pointer to its first item. This conversion is called decay. So readings, holding three, one, four, one, five, becomes the address one thousand. And readings, index two, is exactly star of readings plus two: step forward two items, then look. The int at one thousand eight.
Worked Example
Brackets as Pointer Notation in Code
The brackets are notation for that, and nothing more. That's why an array parameter written with empty brackets is identical to one written as an int pointer. It's what the brackets become. Run it. Index two and star of readings plus two both give four. In the caller, measuring the array gives twenty bytes. Inside the function, the parameter is a pointer, so the measurement is the size of an address. And the last line prints six: the function doubled the caller's first item, through that pointer.
Three Rules, One Fact
Decay Explains Array Parameter Behavior
Once you know about decay, three rules you were asked to accept turn out to be one fact. An array isn't copied into a function. What's passed is a pointer to its first item, one address, whatever the array's size. The function works on the caller's data because that's what the address refers to. The length doesn't travel with it, because an address carries no length. And measuring the array works in the caller, but not in the function. In the caller, the name still refers to the whole array. In the function, the parameter is a pointer, so a measurement reports the size of an address.
Arrow Operator
Reaching Members Through a Pointer
To reach a member of a struct or object through a pointer, you could write star pm, in parentheses, dot id. That's correct, and awkward. The parentheses are compulsory, because the dot binds more tightly than the star. Without them, you'd be trying to dereference pm dot id, which isn't a pointer. So the arrow exists. Pm arrow id means exactly the same thing, written properly, and it works for writing too. That's what you should write. Forget the parentheses and the build fails. Clang says the member reference type is a pointer, and suggests the arrow. If you see that on star pm dot id, the dot bound tighter. Write the arrow.
Const Pointers
Fixed Address Versus Fixed Value
Two different things can be held fixed: the address the pointer holds, or the value it points at. The declarations look alike, and mean opposite things. Read them from the variable name outward. Const int star q is a pointer to const int. It can point elsewhere, but you can't write through it. Int star const r is a const pointer to int. It's fixed on one address, but you can write through it. And with const in both places, neither is allowed. Pointer to const, the q form, is the one you'll write most. Run it: a is nine, written through r. b is five, written through p. And q and s read five and nine. A parameter declared const int star says, I'll look at what you give me, and not change it: the promise a read-only array parameter made earlier. Try to break a promise and the compiler stops you. Writing through q, re-pointing r, and writing through s are all errors, one per line: writing through a const is read-only, and r itself can't be reassigned.
Pointers or References
Choosing a Parameter Style
Pointer parameters and reference parameters both let a function work on the caller's own variable, rather than a copy. They differ in what they permit. The pointer version of add one can, and should, check for null before adding. The reference version needs no check, because it can't be absent. At the call, the pointer version is written with an ampersand, which announces that something may change. The reference version looks like an ordinary call. Inside, a pointer needs a star or an arrow. A reference is bound once, and used like an ordinary variable. Run it: the null call is safely ignored, so count ends at three. So prefer a pointer when the argument is genuinely optional, or must be re-pointed. Prefer a reference for everything else, which is most of the time.
Advanced Note
Pointers to Pointers
A pointer is a variable, so it has an address, so that address can be held in another pointer. Here, p holds the address of count, and pp holds the address of p. The type gains a second star. Each dereference peels off one level. Star star pp goes through both levels to forty-two. You'll meet this mainly in two places: a function that needs to change which thing a caller's pointer points at, shown here by one star pp, and grids built as an array of arrays. It's worth recognizing now, and nothing further here depends on it.
Common Mistakes
Pointer Faults and Their Fixes
Here are faults worth recognizing. A program that stops the moment a pointer is used usually has a pointer never given a value, or a null one. Initialize at declaration, and test against nullptr first. If assigning through a pointer seems to change nothing, the pointer was reassigned, rather than the value written. Star p equals seven writes the value. P equals ampersand x re-points. An address printed where a number was wanted means p was printed, not star p. Measuring an array inside a function gives a tiny number, because the parameter is a pointer. Pass the length. And a build failure on star pm dot id means the dot bound tighter. Write the arrow.
Key Terms
Pointer Vocabulary at a Glance
A few key terms. A pointer is a variable whose value is an address, typed by what it points at. The ampersand produces an address. The star dereferences: the thing at that address. Nullptr means points at nothing, and can be tested for. Decay is the automatic conversion of an array's name to a pointer to its first item. And the arrow reaches a member through a pointer.
Quick Check
Naming n, p, Star p, Ampersand p
Quick check. Given int n of five, and a pointer p holding its address, what do n, p, star p, and ampersand p each denote? Pause and think. N is the value, five. P is n's address. Star p is the value p reaches: five again. And ampersand p is p's own address, because a pointer is a variable too.
Key Takeaways
Pointer Essentials in Five Points
To summarize. The ampersand gives an address, and the star follows one. Initialize every pointer, with nullptr if there's nothing else to point at. Pointer arithmetic moves one whole item of the pointer's type. Arrays decay to pointers, which is why they aren't copied, and their length doesn't travel. And prefer references, using pointers when absence is meaningful.
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. 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 Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming 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 Pointers
What is a pointer in C++, and how do you get and use an address?
Why should I initialize pointers to nullptr instead of leaving them blank?
What is array decay, and why does sizeof give the wrong size inside a function?
What is the difference between const int* q and int* const r?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →