Skip to content

C++ Pointers

Basics

When a variable is created, a memory address is assigned to that variable. And When we assign some value to the variable, the value is stored in that memory address.

We can use & operator to get the memory address of a variable.

show-mem-addr.cpp
#include <iostream>

using namespace std;

int main()
{
    string car = "Tesla";

    cout << car << endl;
    cout << &car << endl;

    return 0;
}

A variable that stores the memory address is a pointer. Be aware that since a pointer points to the memory address of a variable. If we change the value of pointer, the value of original variable would also change.

create-ptr.cpp
#include <iostream>

using namespace std;

int main()
{
    string car = "Tesla";
    string *ptr = &car;

    cout << car << endl;
    cout << &car << endl;
    cout << endl;
    cout << ptr << endl;
    cout << *ptr << endl;
    cout << endl;
    *ptr = "Ford";
    cout << ptr << endl;
    cout << *ptr << endl;

    return 0;
}

Pointer of Array

When using with pointer with an array, we can easily change the pointer's location by adding index.

array-ptr.cpp
#include <iostream>

using namespace std;

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int *ptr = arr;

    for (int i = 0; i < sizeof(arr) / sizeof(int); i++)
    {
        cout << *(ptr + i) << endl;
    }
    return 0;
}

Assignment 16

Write a C++ program named double-down.cpp to find the max of an integer data set and double that maximum. The program will ask the user to input the number of data values in the set and each value. Then the program displays the max value. Later, double the max and display the whole data set.

A sample run looks like the following.

g++ double-down.cpp -o double-down
./double-down
Enter number of values: 5
Enter values in array:
1
2
5
4
3
Max is 5
After doubling down:
1 2 10 4 3
Sample Solution
double-down.cpp
#include <iostream>

using namespace std;

int main()
{
    int n;
    cout << "Enter number of values: ";
    cin >> n;

    cout << "Enter values in array:" << endl;
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }

    int *ptr = arr;
    int max = 0;
    for (int j = 1; j < n; j++)
    {
        if (*(ptr + j) > *(ptr + max))
        {
            max = j;
        }
    }
    cout << "Max is " << *(ptr + max) << endl;

    cout << "After doubling down:" << endl;
    *(ptr + max) = 2 * *(ptr + max);
    for (int j = 0; j < n; j++)
    {
        cout << *(ptr + j) << " ";
    }
    cout << endl;

    return 0;
}

Extra practice

The Kattis Problem Archive is also fun to solve.