Home >Backend Development >C++ >How are pointers and arrays related in C++?

How are pointers and arrays related in C++?

WBOY
WBOYOriginal
2024-06-01 09:52:58861browse

Pointers and arrays are closely related in C++: pointers store variable addresses, while arrays are essentially collections of contiguous memory cells. The array name is a constant pointer pointing to the first element of the array. Pointer arithmetic can be used to iterate over array elements, similar to using array indexing.

指针和数组在 C++ 中有何联系?

The connection between pointers and arrays in C++

In C++, pointers and arrays are closely related, becausearrays Essentially a collection of contiguous memory cells, and pointers store the addresses pointing to these memory cells.

Pointer

  • A pointer is a variable that stores the address of other variables.
  • It allows indirect access to the value of the variable.
  • The type of the pointer must be consistent with the type of the variable it points to.

Array

  • An array is a collection of elements of the same type that are stored contiguously in memory.
  • Each element of the array has a unique index, starting from 0.
  • The array name itself is the address of the first element of the array.

The relationship between pointers and arrays

  • The array name is a constant pointer, which points to the first element of the array.
  • You can access the elements of an array through pointer arithmetic, just like using array indexing.

Practical case

Consider the following C++ code:

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int *ptr = arr;  // ptr 指向 arr

    cout << "Using pointer:" << endl;
    for (int i = 0; i < 5; i++)
        cout << *ptr++ << " ";  // 使用指针运算器访问元素

    cout << "\nUsing array index:" << endl;
    for (int i = 0; i < 5; i++)
        cout << arr[i] << " ";

    return 0;
}

This code demonstrates the use of pointers and array indexes to access array elements, output As follows:

Using pointer: 1 2 3 4 5
Using array index: 1 2 3 4 5

The above is the detailed content of How are pointers and arrays related 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