+ 5
pointer
can anyone explain pointer!
2 Respostas
+ 4
it would be really useful for me if you explain it more
in examples if possible!
+ 2
A pointer contain an address. You can dereference a pointer to access the value pointed.
Example (in C++):
int ans = 42;
//Declaration of a int * variable, assignment of the address of ans to it
//The * here is NOT the dereferencing operator, but is part of the type: int * indicates that this is a pointer pointing to an int
//& is the address-of operator
int *ptr = &ans;
cout << *ptr << endl; //dereferences ptr and prints 42
//Changing the value of ans changes the value of *ptr
//and vice versa (they both refer to the same memory space)
ans = 43;
cout << *ptr << endl; //prints 43
Since pointers just contain an address, if you have a big object and want to pass it as an argument to a function, it is better to pass a pointer to that object instead. Same deal for returned values.
You can also use a reference to pass big objects to a functions. References are like pointers in that they contain an address, but they must reference a variable (while you can set a pointer's value to whatever you want), and there is no need to dereference them. They are like an alias of the variable.
The changes operated by a pointer or reference can persist between function calls. For example, here is a function that takes two references as parameters and swap the value of the two variables (& here is NOT the address-of operator, it indicates that the value is a reference):
//Swaps the value of two variables
void swap(int &a, int &b) {
int tmp = a;
a = b;
b = tmp;
}