topskill.dev
CoursesTracks
0
All courses/C++ ProgrammingPoint to an Existing Value
References and Pointers
4 / 8
← C++ Programming
○Welcome to C++○Change a Message○Write Two Lines○Read a Program○Comments and Spacing○Name a Value○Update a Value○Build an Announcement Card✦Module Quiz
○Choose a Type○Characters and Booleans○Keep a Constant○Arithmetic and Precedence○Division and Remainders○Convert a Number○Format a Price○Calculate a Receipt✦Module Quiz
○Compare Values○Combine Conditions○Choose with if○Choose an Alternative○Choose Between Ranges○Select with switch○Pick a Short Result○Price a Ticket✦Module Quiz
○What Is a Loop?○Repeat with While○Count with For○Build a Running Total○Run at Least Once○Stop or Skip○Rows and Columns○Plan Seating for a Workshop✦Module Quiz
○Return a Result○Pass Arguments○Perform an Action○Keep Names Local○Declare Before Use○Supply a Default Argument○Overload a Function○Build Price Helpers✦Module Quiz
○Store and Join Text○Read Characters Safely○Find and Slice Text○Change a String○Read Values from Text○Write a Text Report✦Module Quiz
○Keep a Fixed Set of Counts○Add Values to a Vector○Visit Every Value○Revise a List Safely○Read Rows and Columns○Recognize a Raw Array○Summarize Shelf Stock✦Module Quiz
○Give a Value Another Name○Read Without Copying a Collection○Let a Function Update the Caller●Point to an Existing Value○Handle a Missing Target○Separate a Fixed Target from Read-Only Access○Keep Borrowed Access Within Its Lifetime✦Module Quiz
○Keep Related Fields in a Struct○Read and Update Records in Functions○Give States Meaningful Names○Keep a Collection of Records○Report Stock by Record and State✦Module Quiz
○Introduce a Class○Initialize with a Constructor○Protect an Invariant○Read a Const Object○Compose Small Objects○Share a Class Constant○Copy an Object○Grant a Friend Access○Build a Basket✦Module Quiz
○Follow a Scope○Observe a Destructor○Allocate and Release○Own with unique_ptr○Transfer Ownership○Prefer the Rule of Zero✦Module Quiz
○Understand Iterators○Sort a Range○Find and Count○Write a Lambda○Capture a Value○Accumulate a Total○Look Up with map○Keep Unique Values○Use a Stack and a Queue○Work at Both Ends○Insert in a List○Organize a Packing List✦Module Quiz
○Organize with Namespaces○Name a Type○Compute with constexpr○Check an Assumption○Write a Function Template○Write a Class Template○Overload an Operator○Pass a Function○Follow Recursion✦Module Quiz
○Extend a Class○Override a Virtual Function○Use an Abstract Base○Avoid Object Slicing○Destroy Through a Base○Check a Derived Type○Choose Composition✦Module Quiz
○Read Binary Flags○Combine Bit Masks○Respect Numeric Limits○Return a Status○Repeat a Random Sequence○Use Math Functions○Diagnose a Wrong Result✦Module Quiz
○Create the Catalog○Find a Book○Lend and Return○Summarize the Shelves○Print the Library Report○Where to Go Next✦Module Quiz

Point to an Existing Value

A reference acts as another name for one object. A pointer is a value that can store an object's address: information that lets the program locate that object. You do not need to print or calculate the numeric address to use it.

Three spellings matter. In a declaration, int* chosen says that chosen is a pointer to an integer. In an expression, &apples obtains the address of apples. In an expression, *chosen follows the pointer to the integer it identifies; this is called dereferencing.

cpp
#include <iostream>
int main() {
    int apples = 6;
    int* chosen = &apples;
    *chosen += 1;
    std::cout << apples << '\n';
}

This prints 7. The pointer does not contain a separate copy of six. It identifies the existing integer, and writing through *chosen updates that integer. Notice how context changes the symbols: & declares a reference beside a type, but takes an address before a variable expression. Similarly, * declares a pointer beside a type and dereferences a pointer expression.

Unlike a reference, an ordinary pointer can be assigned a different address later. Writing chosen = &another changes which object it points to. Writing *chosen = 10 changes the currently selected object's value. Those are not interchangeable operations.

Only dereference a pointer that identifies a live object of the appropriate type. This lesson initializes the pointer immediately and keeps both possible target integers alive for every use. The next lesson introduces the explicit “no object” state.

For the first task, change the address stored when selected is initialized. You are choosing a bin, not changing either bin's count. For the second, leave reservePointer pointing at reserve and add the update through *reservePointer. Keeping these edits separate helps you see which operation changes an address and which changes an integer.

Compare this diagram with the reference diagram: the pointer needs its own stored value, which identifies the target object.

Unlike the reference in the earlier lesson, p is a separate object storing an address. Writing through *p changes score while leaving that address in p unchanged.

Your Task

  1. Initialize selected with the address of largeBin instead of smallBin. Expect Selected units: 12.
  2. Add five through *reservePointer, without assigning directly to reserve. Expect Reserve: 9.

Edit main.cpp, then select Run to inspect the Console. Select Submit to check your completed tasks.

Files
  • ⋄main.cpp
Loading editor…
Press Run to execute your code.