Home > Backend Development > C++ > body text

How does pointer arithmetic work in C++?

王林
Release: 2024-06-03 20:28:02
Original
511 people have browsed it

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!