Are pointers treated as other variables? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Are pointers treated as other variables?

Suppose x is an integer and px is a pointer that holds its address If we give x to a function, the function works with a copy of x and doesn't modify the actual value of x, right? But if we give px to the function, the actual value of x can be modified accessing it by reference, right? Questions: In the second case, does the function work with a copy of px just as in the first case with x? If yes, can px be modified by accessing it by reference with another pointer? (Can a pointer point to a pointer?)

1st Nov 2016, 6:11 PM
Emilio Mécoli
Emilio Mécoli - avatar
1 Answer
+ 1
Yes they are treated the same way. Right and right and yes it is possible to have a pointer that points to another pointer. suppose: int x; int* px = &x; then ppx is the pointer to the pointer px: int** ppx = &px; meaning that ppx holds the address of px and px holds the address of x. you can keep on defining pointers that point to each other ... But about your first question, first you need to make sure you understand the difference between sending pointers and sending variables by refrence to a function. look at the example below: void f(int& x) { x =10; } int main() { int y = 0; f(y); } So here we are sending the argument y by refrence and the function f can directly access y through x( instead of the value of the variable, the function receives its address) But see this one void f(int* x) { int temp; x = &temp; } int main() { int y; int* py = &y; f(py); } Observe that the function receives a copy of the pointer py and that after the execution of the function code, our main function py still holds the address of y and not temp. Hope this clears it up for you :-)
21st Dec 2016, 10:00 PM
S. Saeed Hosseini
S. Saeed Hosseini - avatar