搜尋此網誌

2025年2月11日星期二

Pointer and reference in C++

A pointer is a variable that stores the memory address of another variable.

Declaration: You declare a pointer by using the asterisk * symbol.

A reference is an alias for another variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable.

alias: (computing) a name that can be used instead of the actual name for a file, internet address, etc.

Declaration: You declare a reference using the ampersand & symbol.

Difference: A pointer can be reassigned to point to another variable, but a reference cannot be reassigned.

int* a;    // Declares a as a pointer to an int

int *b;    // Declares b as a pointer to an int

Both declarations are equivalent and will compile the same way. It's often a matter of coding standards or personal preference in a codebase. The most critical thing is to stick to a consistent style throughout your code.

int x;        // Declare an integer x

x = 1;        // Assign the value 1 to x

int y;        // Declare an integer y

y = x;        // Assign the value of x (which is 1) to y

int* ip;      // Declare a pointer to an integer named ip

ip = &x;      // Store the address of x in the pointer ip

y = *ip;      // Assign the value at the address ip points to (which is the value of x) to y

The expression *ip dereferences the pointer ip, meaning it accesses the value stored at the memory address ip points to, which is the value of x.

Since x is 1, *ip is also 1.

The value 1 is then assigned to y.

dereference: to use a piece of data to discover where another piece of data is held

int x {7};

This declares an integer x and initializes it with the value 7 using uniform initialization syntax.

int* ip = &x;

This declares a pointer ip that points to an integer. The pointer ip is initialized with the address of x using the address-of operator &.

Now, ip holds the memory address of x.

int& y = x;

This declares a reference y to the integer x. A reference is an alias for another variable, meaning y and x refer to the same memory location.

Any changes made to y will also be reflected in x since they are effectively the same variable.

If y is assigned the value 11, it directly modifies x to 11 because y is a reference to x.

Copilot

沒有留言:

發佈留言