Get the App
SLTechnology News&Howtos  ›  Network Security  › 

C++ pointer parameter reference

Shulou Source: shulou.com Published: 2022-06-01 06:59:33 10月03日 Update

Stick a code to occupy the position, and there will be time to make up the pointer function and function pointer.

# include using namespace std;void freePtr1 (int* p1) {/ * before releasing memory-> p1 Address: 0012FDDC p1 value: 003429B8, here, p1 it is also a variable, since it is a variable, then it will pass the value of the external variable p1 to the stack, generating an address in the stack: 0012FDDC, of course, its value will still point to the heap address: 003429B8. * / delete p1; / / the system reclaims the memory at the address 003429B8 of the p1 value. P1 = NULL;// assigns a NULL value to p1 that is: 00000000. Note: the address of p1 itself has not changed, but the value of p1 has changed. / / after releasing memory-> p1 Address: 0012FDDC p1 value: 00000000 / /. After unstack, p1 is automatically regarded as invalid because it is a temporary object. } void freePtr2 (int*& p2) {/ * before releasing memory-> p2 Address: 0012FEC8 p2 value: 003429B8, p2 is a reference to a pointer, that is, a reference points to a pointer. Remember the characteristics of the reference: direct operation on the referenced object. So its address and value are the same as the value of p2 in the main () function off the stack. * / delete p2; / / A pair of pointers referenced by p2 releases memory, that is, the system reclaims the memory at the 003429B8 address of the value of p2 in the main () function. P2 = NULL;// assigns null to the pointer to p2 in the main () function. / / after releasing memory-> p2 Address: 0012FEC8 p2 value: 00000000, / / because the objects you operate on are p2 in the main () function, it will be applied to the original variable. } int main () {int * p1 = new int [1]; / / before releasing memory-> p1 Address: 0012FED4 p1 value: 003429B8 freePtr1 (p1); / / after releasing memory-> p1 Address: 0012FED4 p1 value: 003429B8 int * p2 = new int [1]; / / before releasing memory-> p2 Address: 0012FEC8 p2 value: 003429B8 freePtr2 (p2); / / * &. / / after releasing memory-> p2 Address: 0012FEC8 p2 value: 00000000}

Tags: Memory pointers functions addresses variables objects pointing system code location situation time characteristics applications parameters C++ Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Linux Redmi Apple Shulou Technology