搜尋此網誌

2025年9月16日星期二

A classic pointer example in C++

#include <iostream>

using namespace std;


int main() {

    int x = 10;          // a normal integer variable

    int* ptr = &x;       // pointer to int, storing the address of x


    cout << "Value of x: " << x << endl;

    cout << "Address of x: " << &x << endl;

    cout << "Value stored in ptr (address of x): " << ptr << endl;

    cout << "Value pointed to by ptr: " << *ptr << endl; // dereferencing


    // Modify x through the pointer

    *ptr = 20;

    cout << "New value of x after modification via pointer: " << x << endl;


    return 0;

}


int* ptr = &x;ptr stores the address of x.

*ptr → dereferences the pointer, giving access to the value stored at that address.

Changing *ptr actually changes x, since they refer to the same memory location.


Value of x: 10

Address of x: 0x7ffee7b8c9ac

Value stored in ptr (address of x): 0x7ffee7b8c9ac

Value pointed to by ptr: 10

New value of x after modification via pointer: 20


In C++, dereferencing a pointer means accessing the value stored at the memory address the pointer is holding. The operator that does this is the asterisk (*), but only when it’s used outside of a declaration.


Microsoft Copilot

沒有留言:

發佈留言