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.
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
沒有留言:
發佈留言