C++ (2): pointers

what is pointer

A pointer stores a memory address, which points to the location of another data, which can be a variable, array, function, etc. Through the pointer, the data stored in this address can be directly accessed or modified.

define pointer

Notice:定义指针时,总是要初始化它,如果不能确定指针的值,就将其初始化为nullptr

*, &rules to follow

  • address operator&
    • Returns the memory address of the variable
  • dereference operator*
    • When declaring a variable, a pointer type modifier is used to indicate that the variable is a pointer type.
    • In a dereference operation, it means getting the value pointed to by the pointer

Insert image description here

#include <iostream>

using namespace std;

int main() {
   
    
    

    // 空指针
    int *ptr = nullptr;
    cout << ptr << endl; // 0x0
    cout << &ptr << endl; // 0x7ff7bd5d6490

    int a = 123;
    cout << &a << endl; // 0x7ff7bd5d648c
    cout << *&a << endl; // 123

    int *b = &a;
    cout << *b << endl; // 123
    cout << b << endl; // 0x7ff7bd5d648c
    cout << &b << endl; // 0x7ff7bd5d6480

    *b = 456;
    cout << a << endl; // 456
    cout << *b << endl; // 456

    a = 789;
    cout << a << endl; // 789
    cout << *b << endl; // 789


    int x = 123;
    int y = x;
    y = 456;
    cout << x << endl; // 123
    cout << y << endl; // 456

    return 0;
}

Illustration

Insert image description here

Insert image description here

#include <iostream>

using namespace std;

int main() {
   
    
    

    int a = 123;

    cout << a << endl; // 123
    cout << *&a << endl; // 123
    cout << &a << endl; // 0x7ff7b19a6478

    int *b = &a;

    cout << b << endl; // 0x7ff7b19

Guess you like

Origin blog.csdn.net/weixin_43526371/article/details/132403021