CodeBlanks Logo Icon CodeBlanks

Summary - Pointer basics

Combine &, * and nullptr to write a swap function.

Summary - Pointer basics

In this group you learned the core tools of pointers: declaring, taking an address with &, accessing a value with *, the empty state with nullptr, and pointer arithmetic. Pointers unlock the low-level power of C++.

There are two tasks. First, you will write a swap function with two pointer parameters. Second, you will sum the elements of an array using pointer arithmetic. Both combine what you have learned.

Practice The swap(int*, int*) function

Define a void swap(int* a, int* b) function; in the body exchange *a and *b using an int t temporary variable. In main declare int x = 5, y = 9;, call swap(&x, &y), and print x and y on the same line separated by a space.

Starter code

main.cpp
#include <iostream>

// Define the swap function

int main() {
    // Declare x and y
    // Add a swap call
    // Print x and y
    return 0;
}

Sample solution

main.cpp
#include <iostream>

void swap(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main() {
    int x = 5, y = 9;
    swap(&x, &y);
    std::cout << x << " " << y << "\n";
    return 0;
}

Expected output

9 5

Practice Array sum with a pointer

Declare int arr[] = {2, 4, 6};. Start with int* p = arr;. Write int sum = *p + *(p + 1) + *(p + 2); to sum the three elements. Print sum with std::cout.

Starter code

main.cpp
#include <iostream>

int main() {
    // Declare the array
    // Bind p to the array
    // Sum with pointer arithmetic
    // Print the sum
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int arr[] = {2, 4, 6};
    int* p = arr;
    int sum = *p + *(p + 1) + *(p + 2);
    std::cout << sum << "\n";
    return 0;
}

Expected output

12

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does this code print?

main.cpp
void swap(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}
int main() {
    int x = 5, y = 9;
    swap(&x, &y);
    std::cout << x << " " << y;
    return 0;
}
  • 5 9
  • 5 5
  • 9 5 Correct answer
  • Error

Explanation: swap(&x, &y) exchanges the values of x and y.

2 swap call

Question
swap(____, &y);
Answer
swap(&x, &y);

Explanation: swap(&x, &y) passes the addresses of x and y.

3 Match the pointer tools

Term Meaning
int* p Pointer declaration
&x Take address
*p Access value
p + 1 Next element

All lessons in Beginner