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