Pointers in C++

Lesson 11 of 18 · C++

Welcome to the lesson about pointers in C++! In this lesson we will explain in detail what pointers are, how they work, and what their advantages and disadvantages are. You will learn the basic concepts, pointer arithmetic, the connection between pointers and arrays, and ways of allocating memory dynamically. We will also cover more modern approaches, such as smart pointers, which allow safer memory management.

Introduction to pointers

Every piece of data used in a program must be defined, that is, memory must be reserved for it. Giving a value to some data means that this value is stored in binary form at a certain memory location. The data takes as many bits of memory as its data type requires. For example, for data of type int in C/C++ this would be 16 or 32 bits.

Each memory location has its own address. It is a number assigned to the location. The smallest memory location that can be addressed on its own is usually one byte.

A pointer is a simple piece of data that can hold the address of some location in memory.

The data that pointers point to can be of different types.When a piece of data takes several bytes, the address of the data is the byte with the smallest ordinal number.

The address of some data in memory can be obtained with the prefix unary operator &. See more about operators on the page operators in C/C++.

Defining a pointer

* pointer_identifier

Let's look at the following code:

int a = 1;
int *pint;
pint = &a;
cout << a << endl;
cout << pint << endl;

On the standard output:

1
0x61ff18
Figure 1: Showing data through a pointer – example – execution
Setting a value through a pointer – the state of memory
Figure 2: Setting a value through a pointer – the state of memory

An integer a is introduced and initialized to the value 1. A pointer pint to an integer is also introduced and initialized with the memory address of a. Notice that printing the value of the pointer gives a large number in hexadecimal notation. Memory addresses are usually values like this.The data type at the start of the declaration is the type of the data the pointer points to. Above it is int, i.e. the pointer points to an integer. If the data were of type double, a pointer to data of type double would be defined and initialized as follows:

double x = 2;
double *pdbl;
pdbl = &x;

Assigning a value to data through a pointer to other data

If in the previous example we wanted to introduce another piece of data of type double, e.g. y, and initialize it using the pointer to x, we would add the following code:

double x = 2;
double *pdbl;
pdbl = &x;
double y;
y = *pdbl; //y is now 2

Address arithmetic

In C/C++ the following operations on pointers are allowed:

  • assigning the value of one pointer to another
  • ​adding an integer to the value of a pointer and subtracting an integer from the value of a pointer
  • subtracting and comparing two pointers
  • comparing a pointer with zero

Pointers and arrays

Suppose the following array of integers is defined:

int A[7] = {5, -2, 3, 8, 11, 0, 25};

To print the array elements using a pointer, we will introduce the pointer pA and initialize it with the memory address of the first element of the array:

int *pA = A;

To print the value of the array element the pointer points to, use *pA:

std::cout << *pA << "\n";

For the pointer to change the element it points to while the loop runs, it has to be incremented, i.e. its value increased by 1:

pA++;
std::cout << *(pA) << "\n";

or:

std::cout << *(pA + i) << "\n";

In the first cycle, for i = 0 the value of the pointer, i.e. the address of the first element of the array, is e.g. 0xfdf0 (a hexadecimal number), see figure 3. In each cycle the value of the pointer moves by 1 (pA++), which means that the new address will be bigger by the size in bytes of the data the pointer points to. In this case that size is 4 (an int takes 4 bytes). This value would also be obtained with sizeof(int).

In the 4th cycle, e.g. i = 3, so the value of the memory address will be bigger by 3*4=12 bytes, which is also shown in the figure.

Using pointers with arrays. Moving a pointer through the elements of an array
Figure 3: Using pointers with arrays. Moving a pointer through the elements of an array

where the variable "i" changes through the cycles.

The complete code can be seen below:

#include <iostream>
using namespace std;

int main() {
    int A[7] = {5, -2, 3, 8, 11, 0, 25};
    int *pA = A;

    for (int i = 0; i < 7; i++) {
        cout << (pA + i) << "\n";
        cout << *(pA + i) << "\n";
    }

    return 0;
}

If we start the debugger and stop the program inside the loop, we can analyze how the address the pointer points to changes through the cycles when the value of the pointer changes by 1. For i = 3 the pointer moves so that it points to the 4th element of the array, which means that the address increased by 3 * 4 bytes, i.e. from the value 0x61fdf0 (ending in 0) it changes to 0x61fdfc (ending in c, which is the number 12 in hexadecimal).

Using pointers to print the elements of an integer array. The variables shown in the debugger
Figure 4: Using pointers to print the elements of an integer array. The variables shown in the debugger

Pointers and strings

Let a string, i.e. an array of char data, be given as follows:

char text[20] = "Today is a nice day";

The elements of this array are characters, and the last character is '\0'. Read more about strings in C in the article: C strings.

To print these characters on the screen we will use a loop and access the characters with a pointer. Let's define a pointer to data of type char and initialize it with the memory address of the first element of the array tekst:

char *ptr = text;

We will use a while loop and access the characters using a pointer to data of type char. The complete code is shown below.

#include <iostream>
using namespace std;

int main() {
    char text[20] = "Today is a nice day";
    char *pText = text;

    while (*pText != '\0') {
        cout << *pText << "\n"; // Prints the character that the pointer pText points to

        pText++; // Moving the pointer to the next character
    }

    return 0;
}

The condition checked in the while loop is that the code of the current character is different from the code of the last character, i.e. different from '\0'.

Moving the pointer to point to the next character is done by increasing the value of the pointer by 1. In this case the size of a char is 1 byte, so the address the pointer points to will change in each cycle by 1 byte and not by 4 bytes, as was the case with data of type int.

After running the program, the following is shown:

T
o
d
a
y
 
i
s
 
a
 
n
i
c
e
 
d
a
y
Figure 5: Using pointers to print the characters of a string. Running the program

Test your code in the editor below!

#include <iostream>
using namespace std;

int main() {
    // Write your C++ code here...
    cout << "Hello!" << endl;
    return 0;
}

Practical examples: dynamic memory allocation

Dynamic memory allocation is a key concept in programming that allows efficient management of memory while a program runs. This technique lets you create variables and structures whose size is not known in advance, which is especially useful for working with large data, matrices and dynamic structures such as lists or trees. In this section we look at practical examples that include allocating, initializing and freeing memory, with explanations of how to avoid common mistakes such as memory leaks. Master the basics through clearly explained code and step-by-step instructions!

1. Creating and freeing a dynamic array

The example shows basic dynamic allocation and freeing of memory for an array, including printing the elements.

#include <iostream>
using namespace std;

// Dynamic memory allocation for an array
int main() {
    int *arr = new int[10]; // Dynamic allocation of an array of size 10

    // Filling the array with values and printing
    for (int i = 0; i < 10; ++i) {
        arr[i] = i * 2; // Each element gets the value i * 2
        cout << arr[i] << " "; // Printing the element
    }

    // Freeing the memory after use
    delete[] arr; // Prevents a memory leak

    return 0; // End of the program
}

2. Dynamic objects with a constructor and a destructor

The example shows working with a dynamically allocated object of a class, with a constructor and a destructor, including freeing the memory.

#include <iostream>
using namespace std;

// Definition of the class Student
class Student {
  public:
    string name; // Attribute that holds the student's name

    Student(string i)
        : name(i) {} // Constructor that sets the student's name
    ~Student() {
        cout << "Student " << name << " has been deleted." << endl; // Destructor that prints a message when the object is deleted
    }
};

int main() {
    Student *s = new Student("Marko"); // Dynamic allocation of a Student object
    cout << s->name << endl; // Printing the student's name
    delete s; // Calls the destructor and frees the memory

    return 0; // End of the program
}

Explanation:

  • Constructor: When a Student object is created with new, the constructor Student(string i) is called, which sets the student's name.
  • Destructor: When the object is deleted with delete, the destructor ~Student() is called. It prints a message that the object has been deleted, which is useful for following the life of the object in memory.
  • Dynamic allocation: Using new we allocate the object on the heap, and delete frees that memory.

3. A matrix as a pointer to pointers

The example shows how to use dynamic memory allocation for a matrix with pointers to pointers. This approach allows flexible memory management for two-dimensional structures, but it requires freeing the memory correctly to avoid leaks.

#include <iostream>
using namespace std;

// Dynamic allocation of a matrix as a pointer to pointers
int main() {
    int **matrix = new int *[3]; // Allocating the array of row pointers

    // Allocating the columns and filling the matrix
    for (int i = 0; i < 3; ++i) {
        matrix[i] = new int[4]; // Allocating each row
        for (int j = 0; j < 4; ++j) {
            matrix[i][j] = i + j; // Filling the matrix with values
        }
    }

    // Printing the matrix
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 4; ++j) {
            cout << matrix[i][j] << " "; // Printing each element
        }
        cout << endl; // New line
    }

    // Freeing the memory
    for (int i = 0; i < 3; ++i) {
        delete[] matrix[i]; // Freeing each row
    }
    delete[] matrix; // Freeing the pointer to pointers

    return 0;
}

4. Working with a pointer in a function

This example shows how functions can work with dynamically allocated memory using pointers. The function takes a pointer as a parameter, which allows it to change the value at that memory location directly. This approach allows efficient work with data in memory.

#include <iostream>
using namespace std;

// Function for initializing a value
void initialize(int *p, int value) {
    *p = value; // Sets the value at the memory location
}

int main() {
    // Dynamic memory allocation for an integer
    int *number = new int;

    // Calling the initialization function
    initialize(number, 42);

    // Printing the value
    cout << *number << " "; // Prints 42

    // Freeing the memory
    delete number;

    return 0;
}

Explanations:

  1. The function initialize:
    • Takes the pointer p and the value value.
    • Directly changes the value at the memory location that p points to.
  2. Dynamic allocation:
    • The pointer number allocates space for an integer in memory with new int.
  3. Calling the function:
    • The function initialize sets the value at the memory location, which allows that value to be accessed and changed later.
  4. Freeing the memory:
    • Memory taken with new int must be freed with delete to avoid a memory leak.

5. Dynamic memory allocation for a vector

This example shows the use of dynamic memory allocation for a vector and demonstrates operations such as adding elements and printing the contents. This approach is useful when the size of the data structure is not known in advance.

#include <iostream>
#include <vector>
using namespace std;

// Working with a dynamically allocated vector
int main() {
    vector<int> vec; // Declaring a dynamic vector

    // Adding elements to the vector
    for (int i = 0; i < 5; ++i) {
        vec.push_back(i * 3); // Adds the value i * 3 to the end of the vector
    }

    // Printing the elements of the vector
    for (int i : vec) {
        cout << i << " "; // Printing each element
    }

    return 0; // End of the program
}

6. Dynamic allocation of a data structure

This example shows how to use dynamic allocation for a data structure. Structures are useful for grouping related data, while dynamic allocation is used for flexible memory management.

#include <iostream>
using namespace std;

// Defining the structure
struct Person {
    string name; // The person's name
    int age; // The person's age
};

int main() {
    Person *person = new Person; // Dynamic allocation for the structure

    // Giving values to the members of the structure
    person->name = "Marko";
    person->age = 25;

    // Printing information about the person
    cout << "Name: " << person->name << ", Age: " << person->age << endl;

    // Freeing the memory
    delete person;

    return 0;
}

Comparison with references

Pointers and references are key concepts in C++ that allow indirect work with variables, but they differ significantly in syntax, functionality and use. A pointer stores an address in memory and can be changed to point to another object, while a reference is an alias (another name) for an existing object and cannot be reassigned. References are simpler and safer to use, while pointers give more flexibility, especially for dynamic memory allocation. Below we will explain these differences in detail through practical examples.

Example

#include <iostream>
using namespace std;

// Function that uses a pointer to change a value
void changeWithPointer(int *ptr) {
    *ptr = 10; // Changes the value the pointer points to
}

// Function that uses a reference to change a value
void changeWithReference(int &ref) {
    ref = 20; // Changes the value directly through the reference
}

int main() {
    int number = 5; // Initializing the variable

    cout << "Starting value: " << number << endl;

    // Using a pointer
    changeWithPointer(&number); // Passes the address of the variable
    cout << "After changing with a pointer: " << number << endl;

    // Using a reference
    changeWithReference(number); // Passes a reference to the variable
    cout << "Nakon izmene referencom: " << number << endl;

    return 0; // End of the program
}

Explanation:

  1. Pointer: The function changeWithPointer takes the address of a variable (int* ptr) and uses dereferencing (*ptr) to change the value at that address.
  2. Reference: The function changeWithReference uses a reference (int& ref), which is an alias for the variable, allowing the value to be changed directly.

Difference in use:

  • Pointers require explicitly passing the address (&) and dereferencing (*).
  • References are more intuitive because they behave like ordinary variables without extra syntax.

Modern standards in C++: smart pointers and RAII

Since the C++11 standard, smart pointers such as std::unique_ptr and std::shared_ptr have been introduced, which make managing dynamically allocated memory much easier. They apply the RAII principle (Resource Acquisition Is Initialization), which means that resources are freed automatically when the object goes out of scope. This approach reduces the risk of memory leaks and other mistakes connected with managing memory by hand (using new and delete).

Advantages of using smart pointers:
- Automatic freeing of memory: you don't have to call delete or delete[] yourself.
- Safety: mistakes such as freeing memory twice are avoided.
- Simpler code: the code becomes easier to read and maintain, because resources are managed automatically.

The next example shows how std::unique_ptr and std::shared_ptr are used in practice:

#include <iostream>
#include <memory>

// Example class used for the demonstration
class Example {
  public:
    void show() {
        std::cout << "This is an example of a smart pointer." << std::endl;
    }
};

// Main function
int main() {
    // Using std::unique_ptr: guarantees sole ownership of the object
    std::unique_ptr<Example> uniquePtr = std::make_unique<Example>();
    uniquePtr->show();

    // Using std::shared_ptr: several pointers share ownership of the same object
    std::shared_ptr<Example> sharedPtr1 = std::make_shared<Example>();
    std::shared_ptr<Example> sharedPtr2 = sharedPtr1; // Both pointers share the same object
    sharedPtr2->show();

    return 0;
}

As you can see, std::unique_ptr guarantees sole ownership, while std::shared_ptr allows ownership to be shared between several pointers. This modern approach makes code safer and easier to maintain, which is especially important in complex projects.

Additional explanation:
Smart pointers and RAII principles are key elements of modern C++ programming, so it is a good idea to know them well and use them in your own code.

A more detailed analysis of mistakes when working with pointers

When working with pointers in C++, mistakes often happen that can cause serious problems in a program, such as memory leaks and dangling pointers. Below are examples of common mistakes, with suggested solutions and ways to prevent them.

Memory leak

A memory leak happens when dynamically allocated memory is not freed correctly, which can gradually reduce the available memory and slow the program down.

// Example of a memory leak
int *leak() {
    int *p = new int[10];
    return p; // The memory is not freed, which can lead to a memory leak
}

int main() {
    int *arr = leak();
    /* Using the array */
    delete[] arr; // If this delete is left out, there will be a memory leak
    return 0;
}

Solution: Use smart pointers, such as std::unique_ptr or std::shared_ptr, which automatically free memory when the object is no longer used.

// Solution with std::unique_ptr
#include <memory>
#include <iostream>
std::unique_ptr<int[]> leakFixed() {
    return std::make_unique<int[]>(10);
}

int main() {
    auto arr = leakFixed();
    // The array will be freed automatically when it goes out of scope
    std::cout << "Smart pointers prevent memory leaks." << std::endl;
    return 0;
}

Dangling pointers

Dangling pointers appear when a pointer refers to memory that has been freed or no longer exists. Using such pointers can lead to unpredictable behavior and program crashes.

#include <iostream>

// Example of a dangling pointer
int *dangling() {
    int a = 42;
    return &a; // Returns the address of a local variable, which will be destroyed after leaving the function
}

int main() {
    int *p = dangling();
    // Attempt to access freed memory
    std::cout << *p; // Unreliable: p points to an invalid memory location
    return 0;
}

Preventive measures:
- Never return the address of a local variable from a function.
- If a function needs to return a pointer, use dynamic allocation or smart pointers.
- After freeing memory, set the pointer to nullptr to prevent unwanted access.

Applying these preventive measures and using modern memory management techniques greatly reduces the chance of mistakes when working with pointers in C++.

Additional documentation

For those who want to deepen their knowledge of modern C++ techniques and practices, we recommend the following resources. They include books, blogs and forums that are regularly updated and give real-world examples.

These resources offer a wide range of information – from the basics of the language to advanced techniques and practices. We recommend them to everyone who wants to keep up with the latest standards and improve their programming skills in C++.

Check your knowledge

Open the quiz

Quiz: Pointers in C++

1. What is &x?




2. If int *p = &x;, what is *p?




3. What must follow every new?




4. What is nullptr?