Pointers

Memory Addresses and Pointers

Any object in memory that is active when your program is running has a location, called its address. You can use C++ to get the address of an object and have your program store it in a special variable called a pointer.

#include <iostream>

int main()
{
    int score = 42;

    std::cout << &score << '\n';

    return 0;
}

You define a normal integer score and set it to 42. The code &score asks the program for the address of score. The address is then printed. The particular number you see depends on the compiler, but the principle remains; the program can obtain the location.

You define a variable called a pointer. The task of a pointer is to hold an address.

#include <iostream>

int main()
{
    int score = 42;
    // Store this object address in the pointer
    int* ptr = &score;

    std::cout << ptr << '\n';

    return 0;
}

When you define int* ptr, you are saying that ptr is a pointer to an int. When you initialize it to &score, you put the address of score into ptr. Printing ptr now prints the address of score. Remember, ptr is not 42; it is the address where 42 can be found.

Once your pointer has an address stored in it, you can use it to refer to the object at that address. Simply put an asterisk before the pointer variable when you are using the pointer:

#include <iostream>

int main()
{
    int score = 42;
    int* ptr = &score;

    std::cout << *ptr << '\n';

    return 0;
}

The expression *ptr means "get the int stored at the address pointed to by ptr". Since ptr points to score, *ptr evaluates to 42. So 42 is printed. Changing the value at a pointer changes the referenced object:

#include <iostream>

int main()
{
    int score = 42;
    int* ptr = &score;

    // Dereference the pointer to modify the pointed-to object
    *ptr = 100;

    std::cout << score << '\n';

    return 0;
}

The code *ptr = 100 actually changes the value of score to 100. The final printout prints 100. When they look the same, score and *ptr are identical concepts.

A pointer can be assigned to "no address" by assigning nullptr to it.

#include <iostream>

int main()
{
    // Use nullptr when the pointer refers to no object
    int* ptr = nullptr;

    std::cout << ptr << '\n';

    return 0;
}

Now ptr does not have an address to put in it, and the program typically prints 0. Do not attempt to dereference a null pointer. It will produce undefined behavior, like the commented line below.

#include <iostream>

int main()
{
    int* ptr = nullptr;

    // std::cout << *ptr << '\n'; // Undefined behavior

    return 0;
}

This would ask the program to fetch an int from address 0, or a similar value representing null depending on the machine. The language does not specify what happens at this point; it might be a crash, or it might just work incorrectly with whatever junk happens to be stored at address zero.

A pointer has an address, or at least it can have an address. Before a pointer is assigned the address of any valid object, its address cannot be guaranteed to have any special value.

#include <iostream>

int main()
{
    int* ptr;

    // std::cout << *ptr << '\n'; // Undefined behavior

    return 0;
}

This pointer has no value assigned; its address is random. You must never dereference an undefined pointer, or the behavior is undefined, and the program may crash or act weird.

Also, pointer types matter. You can have a pointer to an integer, a pointer to a string, a pointer to a structure, etc. A pointer to an integer can never have the address of a string placed into it without a direct cast of the value of the address.

#include <iostream>

int main()
{
    int score = 42;
    double temperature = 36.6;

    int* ptr = &score;
    // int* bad = &temperature; // Type mismatch

    std::cout << *ptr << '\n';

    return 0;
}

Here ptr is pointing to a legitimate object score. The next line is flagged, as you cannot directly assign the address of a double to a pointer to an int without a cast. The type of a pointer determines how many bytes you would access for that object.

Exercise: Memory Addresses and PointersStarter code, hints and solutionOpenClose
Guided practiceBeginner · 10–15 min

Practice: Memory Addresses and Pointers

Work through the mission, reveal hints only when needed, and compare your result with the model solution.

Your challenge

Verify ptr points to score, assign 75 through it, then clear ptr and report that it is empty. Explain why no delete is needed for score.

Mission checklist

  1. Run the starter as a baseline, then predict the change requested in Your challenge.
  2. Make that change in your editor; use the lesson-specific hints if you need help.
  3. Compile and run your answer, then compare with the worked solution and explain the result.

Starter program

This is the working baseline, not the completed answer. Compile as C++20, then make the change described above.

#include <iostream>

int main()
{
    int score = 42;
    int* ptr = &score;

    // Dereference the pointer to modify the pointed-to object
    *ptr = 100;

    std::cout << score << '\n';

    return 0;
}

Hints

Hint 1

ptr stores the address of score; *ptr refers to score itself. There is only one int object being changed by *ptr = 100.

Hint 2

Change the value assigned through *ptr and predict std::cout << score. This pointer does not own dynamically allocated memory, so do not delete it.

Worked solution

ptr is acquired from &score and never owns a dynamic allocation. The new equality check identifies its target. Writing 75 through *ptr changes score; setting ptr to nullptr only clears the pointer and does not destroy score.

#include <iostream>

int main()
{
    int score = 42;
    int* ptr = &score;

    // Dereference the pointer to modify the pointed-to object
    *ptr = 100;

    std::cout << score << '\n';

    std::cout << "Targets score: " << (ptr == &score) << '\n';
    *ptr = 75;
    std::cout << "Score after write: " << score << '\n';
    ptr = nullptr;
    std::cout << "Pointer empty: " << (ptr == nullptr) << '\n';
    return 0;
}

Example output

100
Targets score: 1
Score after write: 75
Pointer empty: 1

0 comments

No comments yet. Be the first.

Add a comment

About CppLearn

CppLearn is an interactive, free reference for modern C++. In each lesson, you'll find out how the language works, rather than just lines of code that you can copy and paste. We cover concepts starting from beginner lessons on fundamentals and proceed to templates, move semantics, smart pointers, and areas that usually trap or scare C++ learners.