Learn with Yasir

Share Your Feedback

Lecture: Pointer Arithmetic and Pointers with Arrays in C++


Lecture: Pointer Arithmetic and Pointers with Arrays in C++

Course: Programming Fundamentals (CS-303)
Topic: Pointer Arithmetic and Pointers with Arrays
Level: Beginner
Language: C++

1. Learning Objectives

By the end of this lecture, students will be able to:

  1. Understand pointer arithmetic.
  2. Perform arithmetic operations on pointers.
  3. Understand the relationship between arrays and pointers.
  4. Access array elements using pointers.
  5. Traverse arrays using pointers.
  6. Understand the difference between array indexing and pointer notation.

2. Introduction to Pointer Arithmetic

In C++, pointers can be used in arithmetic operations to move between memory locations.

Unlike normal integer arithmetic, pointer arithmetic depends on the data type of the pointer.

For example:

int number = 10;

int *ptr = &number;

cout << ptr << endl;
cout << ptr + 1 << endl;

Explanation:

  • ptr stores the address of number.
  • ptr + 1 moves the pointer to the next integer memory location.
  • If an integer occupies 4 bytes, the address increases by 4 bytes.

C++ Pointers and Arrays

programiz.com

Important: Pointer arithmetic moves according to the size of the data type, not simply one byte.

3. Pointer Arithmetic Operations

C++ supports the following pointer arithmetic operations:

Operation Description
ptr++ Move to the next element
ptr-- Move to the previous element
ptr + n Move forward by n elements
ptr - n Move backward by n elements
ptr2 - ptr1 Calculate the distance between two pointers

Example 1: Incrementing a Pointer

#include <iostream>
using namespace std;

int main()
{
    int num = 50;

    int *ptr = &num;

    cout << "Address: " << ptr << endl;

    ptr++;

    cout << "After increment: " << ptr << endl;

    return 0;
}

Understand:

If int occupies 4 bytes, incrementing the pointer moves it forward by 4 bytes.

Note: In this example, incrementing the pointer moves it outside the valid object. We are demonstrating the arithmetic only; do not dereference it.

Example 2: Pointer Increment with an Array

#include <iostream>
using namespace std;

int main()
{
    int numbers[4] = {10, 20, 30, 40};

    int *ptr = numbers;

    cout << *ptr << endl;

    ptr++;

    cout << *ptr << endl;

    return 0;
}

Output:

10
20

Explanation:

  1. ptr = numbers stores the address of the first array element.
  2. *ptr accesses the first element.
  3. ptr++ moves the pointer to the next element.
  4. *ptr now accesses the second element.

4. Relationship Between Arrays and Pointers

In C++, an array name usually behaves like a pointer to its first element when used in an expression.

Consider:

int numbers[5] = {10, 20, 30, 40, 50};

int *ptr = numbers;

Both expressions refer to the first element:

numbers
&numbers[0]

Therefore:

cout << numbers[0] << endl;
cout << *ptr << endl;

Both produce:

10

Pointer Explained at Margaret Burgin blog

storage.googleapis.com

Remember:

int *ptr = numbers;

is equivalent to:

int *ptr = &numbers[0];

However, an array name is not itself a modifiable pointer variable. You cannot write numbers++.

5. Accessing Array Elements Using Pointers

We can access array elements using pointer notation instead of array indexing.

Consider the following array:

int numbers[5] = {10, 20, 30, 40, 50};
Array notation Pointer notation Value
numbers[0] *(numbers + 0) 10
numbers[1] *(numbers + 1) 20
numbers[2] *(numbers + 2) 30
numbers[3] *(numbers + 3) 40
numbers[4] *(numbers + 4) 50

Important Formula:

\[ numbers[i] = *(numbers+i) \]

Both notations access the same array element.

Example 3: Accessing Array Elements Using Pointer Notation

#include <iostream>
using namespace std;

int main()
{
    int numbers[5] = {10, 20, 30, 40, 50};

    cout << *(numbers + 0) << endl;
    cout << *(numbers + 1) << endl;
    cout << *(numbers + 2) << endl;
    cout << *(numbers + 3) << endl;
    cout << *(numbers + 4) << endl;

    return 0;
}

Output:

10
20
30
40
50

6. Traversing an Array Using Pointers

We can use a pointer and a loop to access all elements of an array.

Example 4: Display Array Elements Using a Pointer

#include <iostream>
using namespace std;

int main()
{
    int numbers[5] = {10, 20, 30, 40, 50};

    int *ptr = numbers;

    for (int i = 0; i < 5; i++)
    {
        cout << *ptr << endl;

        ptr++;
    }

    return 0;
}

Output:

10
20
30
40
50

Dry Run:

Iteration Pointer position *ptr Output
1 numbers[0] 10 10
2 numbers[1] 20 20
3 numbers[2] 30 30
4 numbers[3] 40 40
5 numbers[4] 50 50

7. Calculating the Sum of Array Elements Using Pointers

We can also perform calculations using pointers.

Example 5: Calculate the Sum

#include <iostream>
using namespace std;

int main()
{
    int numbers[5] = {10, 20, 30, 40, 50};

    int *ptr = numbers;

    int sum = 0;

    for (int i = 0; i < 5; i++)
    {
        sum = sum + *ptr;

        ptr++;
    }

    cout << "Sum = " << sum << endl;

    return 0;
}

Output:

Sum = 150

Explanation:

  • The pointer starts at the first array element.
  • *ptr reads the current element.
  • The element is added to sum.
  • ptr++ moves to the next element.
  • The loop continues until all elements are processed.

8. Difference Between Array Indexing and Pointer Notation

Array Indexing Pointer Notation
numbers[0] *numbers
numbers[1] *(numbers + 1)
numbers[2] *(numbers + 2)
numbers[i] *(numbers + i)

Both methods can access array elements.

Array indexing is generally easier to read, while pointer notation helps understand how arrays and memory addresses are related.

9. Pointer Comparison

Pointers that point to elements of the same array can be compared.

Example:

#include <iostream>
using namespace std;

int main()
{
    int numbers[4] = {10, 20, 30, 40};

    int *ptr1 = &numbers[0];
    int *ptr2 = &numbers[3];

    if (ptr1 < ptr2)
    {
        cout << "ptr1 comes before ptr2";
    }

    return 0;
}

Output:

ptr1 comes before ptr2

10. Important Rules of Pointer Arithmetic

  1. Pointer arithmetic depends on the pointer’s data type.
  2. ptr++ moves to the next element.
  3. ptr-- moves to the previous element.
  4. Pointer arithmetic should remain within an array or one position past its end.
  5. A one-past-the-end pointer must never be dereferenced.
  6. Adding two pointers is not allowed.
  7. Multiplication and division of pointers are not allowed.
  8. Pointer subtraction is valid for pointers into the same array (or one position past it).

11. Common Mistakes

Incorrect Code Reason
ptr = ptr + 1; when ptr is uninitialized Invalid pointer use
*ptr++ without checking array bounds May dereference an invalid position
numbers++ Array name cannot be modified
ptr1 + ptr2 Adding two pointers is not allowed
*(numbers + 5) for an array of size 5 Out-of-bounds access

12. Practice Exercises

Exercise 1: Display Array Elements

Write a C++ program that:

  • Declares an integer array of five elements.
  • Initializes it with values.
  • Uses a pointer to display all elements.
  • Uses pointer increment to move through the array.

Exercise 2: Calculate the Sum

Write a C++ program that:

  • Declares an array of six integers.
  • Uses a pointer to access each element.
  • Calculates and displays the sum of all elements.

Exercise 3: Find the Largest Element

Write a C++ program that:

  • Declares an array of five integers.
  • Uses a pointer to traverse the array.
  • Finds and displays the largest element.

Exercise 4: Display Array in Reverse Order

Write a C++ program that:

  • Declares an array of five integers.
  • Uses a pointer to access the last element.
  • Moves the pointer backward.
  • Displays all elements in reverse order.

Exercise 5: Modify Array Elements

Write a C++ program that:

  • Declares an array of five integers.
  • Uses a pointer to access each element.
  • Multiplies every element by 2.
  • Displays the updated array.

13. Quick Assessment (MCQs)

Q1. What does ptr++ do when ptr points to an integer array element?

  • A. Moves one byte forward
  • B. Moves to the next integer element
  • C. Moves to the previous element
  • D. Deletes the current element

Q2. What is the output?

int arr[3] = {10, 20, 30};
int *ptr = arr;

cout << *(ptr + 2);
  • A. 10
  • B. 20
  • C. 30
  • D. Address of arr

Q3. Which expression is equivalent to arr[1]?

  • A. *(arr + 1)
  • B. *(arr + 2)
  • C. *arr + 1
  • D. arr++

Q4. What does ptr-- do?

  • A. Moves to the next element
  • B. Moves to the previous element
  • C. Deletes an element
  • D. Changes the array size

Q5. Which operation is not allowed?

  • A. ptr++
  • B. ptr + 2
  • C. ptr - 1
  • D. ptr1 + ptr2

14. Lecture Summary

In this lecture, we learned:

  • Pointer arithmetic and memory movement.
  • Pointer increment and decrement.
  • The relationship between arrays and pointers.
  • Accessing array elements using pointer notation.
  • Traversing arrays using pointers.
  • Performing calculations using pointers.

Key Concepts to Remember

int *ptr = numbers;

*ptr       // First element
*(ptr + 1) // Second element
*(ptr + 2) // Third element

ptr++;     // Next element
ptr--;     // Previous element

Remember: Array indexing and pointer notation can access the same array elements.