搜尋此網誌

2025年8月5日星期二

Pointer in C++

#include <iostream>

void incrementByPointer(int* ptr) {
    if (ptr) {
        (*ptr)++;  // Dereference pointer, then increment the pointee
    }
}

Line 1. Function Signature - Return type is void, so nothing comes back to the caller. - Parameter is int* ptr, a pointer to an int.

Line 2. Null Check
Guarding against a null pointer prevents undefined behavior if someone accidentally calls
incrementByPointer(nullptr).

Line 3. Dereference & Increment
- The parentheses ensure you dereference ptr first, yielding the int it points to.
- The ++ then increments that int in place.
Note: Writing ptr++ would advance the pointer itself, not the value it points to.

int main() {
    int value = 10;
    int* pValue = &value;  // Declare a pointer and take the address of 'value'
   
    std::cout << "Before: " << value << "\n";  // Prints 10
   
    incrementByPointer(pValue);
   
    std::cout << "After:  " << value << "\n";  // Prints 11

When you see both ptr and pValue in the code, they’re actually two separate pointer variables that refer

to the same int in memory, but they live in different scopes and serve different roles.

Roles and Scope

    pValue

Declared in main().

Holds the address of value.

Its lifetime is the entire execution of main.

You use it to pass &value into functions or perform pointer arithmetic in main.

    ptr

Declared as a parameter in incrementByPointer(int* ptr).

Receives a copy of pValue (the address).

Its lifetime is the duration of the function call.

You use it inside incrementByPointer to modify the pointee.


The literal "\n" represents a single newline character in C++ strings.

When inserted into an output stream, it moves the cursor to the beginning of the next line.

    // Pointer arithmetic example
    int arr[] = {1, 2, 3};
    int* pArr = arr;  // Points to the first element
    std::cout << "Second element via pointer arithmetic: "
              << *(pArr + 1) << "\n";  // Prints 2
   
    return 0;
}

arr decays to int* pointing at the first element.

pArr + 1 advances the pointer by one int (4 bytes on most platforms).

The dereference *(pArr+ 1) yields the second element, exactly like arr[1].

Output:

Second element via pointer arithmetic: 2


Microsoft Copilot

沒有留言:

發佈留言