Home  >  Article  >  Backend Development  >  How does pointer arithmetic work in C++?

How does pointer arithmetic work in C++?

王林
王林Original
2024-06-03 20:28:02534browse

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.

指针的算术运算在 C++ 中如何工作?

How pointer arithmetic works in C++

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

  • Adding an integer to a pointer will add the corresponding number of bytes to the address pointed to by the pointer.
  • For example, if 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

  • Subtracting an integer from a pointer will reduce the corresponding number of bytes at the address pointed to by the pointer.
  • Similar to the addition operation, it is used to access earlier elements in an array or string.

Multiplication operations

  • Multiplying a pointer by an integer representing the size of the element causes the pointer to point to the element at the corresponding index in the array or string.
  • For example, if the size of each element in the array 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn