C++ Pointer Arithmetic šŸŽÆ

beginner
15 min

C++ Pointer Arithmetic šŸŽÆ

Welcome to our deep dive into C++ Pointer Arithmetic! This lesson is designed to help you understand and master pointer arithmetic, a crucial concept in C++ programming. Let's get started!

Understanding Pointers šŸ“

Before we delve into pointer arithmetic, let's briefly recap what pointers are. A pointer in C++ is a variable that stores the memory address of another variable.

cpp
int num = 10; int *ptr = # // ptr is a pointer that stores the address of num

Pointer Arithmetic Basics šŸ’”

Pointer arithmetic allows you to manipulate memory addresses. With pointers, you can:

  • Increment (++) or decrement (--) a pointer to move to the next or previous memory location.
  • Access the memory location pointed to by a pointer using the dereference operator (*).

Here's an example:

cpp
int numbers[3] = {1, 2, 3}; int *ptr = numbers; // Print the first element cout << *ptr << endl; // Output: 1 // Move to the next element ptr++; // Print the second element cout << *ptr << endl; // Output: 2

šŸ“ Note: You can also decrement a pointer to move to a previous memory location. For example, ptr-- moves the pointer to the previous memory location.

Pointer Arithmetic Rules šŸ’”

  1. A pointer can be incremented or decremented by any integral type (e.g., int, char, etc.).
  2. When you increment a pointer that points to the end of an array, it will wrap around to the beginning of the array.
  3. When you decrement a pointer that points to the beginning of an array, it will wrap around to the end of the array.

Pointer Arithmetic and Arrays šŸ’”

Pointer arithmetic can be used to iterate through arrays. Here's an example:

cpp
int numbers[5] = {1, 2, 3, 4, 5}; int *ptr = numbers; for (int i = 0; i < 5; i++) { cout << *ptr++ << endl; }

This code outputs 1 2 3 4 5, demonstrating how pointer arithmetic can be used to iterate through an array.

Pointer Arithmetic and Strings šŸ’”

Pointer arithmetic is also commonly used with strings. Since strings in C++ are arrays of characters, you can use pointer arithmetic to manipulate them.

cpp
char message[] = "Hello, World!"; char *ptr = message; // Print the first character cout << *ptr << endl; // Output: H // Move to the next character ptr++; // Print the next character cout << *ptr << endl; // Output: e

Pointer Arithmetic Quiz šŸ’”

Quick Quiz
Question 1 of 1

What does the following code output?

And there you have it! You've learned the basics of C++ Pointer Arithmetic. As you continue to practice and apply these concepts, you'll become more comfortable with pointer arithmetic in your C++ projects. Happy coding! šŸš€šŸŒŸšŸ’»