Home > Article > Backend Development > How does pointer arithmetic work in C++?
Pointer arithmetic is a way of manipulating pointers in C++, allowing addition, subtraction, and multiplication operations on pointers. These operations can be used to access array elements and string characters.
A pointer is a type of variable that stores the address of other variables. Pointer arithmetic allows addition, subtraction, and multiplication of pointer values. This is useful when accessing array elements and string characters.
Addition operation
ptr
points to the address of a variable of type int
, ptr + 1
will point to the next int
The address of the element. Subtraction operation
Multiplication operations
arr
is 4 bytes, arr[2]
is equivalent to *(arr + 2)
. Practical case
The following is a C++ program fragment showing pointer arithmetic:
#include <iostream> using namespace std; int main() { // 定义一个数组 int arr[] = {1, 2, 3, 4, 5}; // 获得数组第一个元素的指针 int *ptr = arr; // 使用指针算术访问数组元素 cout << *ptr << endl; // 输出 1 cout << *(ptr + 1) << endl; // 输出 2 return 0; }
The above is the detailed content of How does pointer arithmetic work in C++?. For more information, please follow other related articles on the PHP Chinese website!