Why do we need the address of a variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why do we need the address of a variable?

Look title.

12th Dec 2018, 3:15 PM
Platinoob_
Platinoob_ - avatar
3 Answers
+ 2
Juan David Padilla Diaz In fact, you don't need a pointer in this case. This would work perfectly, with exactly the same result: int x = 5; int p = x; cout << p; // Outputs 5 A pointer would be needed, for example, here: void change_num (int *num) { *num = 10; } int main () { int x = 5; change_num(x); cout << x; // Outputs 10 return 0; } The function can only change the variable because it receives a pointer to its address, so it writes there. If we send only the value - like in change_num(int num) - the function could change the number, but not the variable which has the number in the main function. change_num needs to know where to write.
14th Dec 2018, 11:09 AM
Emerson Prado
Emerson Prado - avatar
+ 1
I will use this example to explain you. int x = 5; int *p = x; cout<<p; output: error, because the conversion of int to int*(pointer) cant be done like that because it's different. So if we want to store a value in a pointer from another variable we need the address of the value that we want to store in memory, so we use an address to tell to the pointer that the value we want to store from another variable it's located in the following address so it can be stored. int x = 5; int *p =&x://address to the value cout<<*p; output : 5
14th Dec 2018, 1:53 AM
Juan David Padilla Diaz
Juan David Padilla Diaz - avatar
0
To send it to functions so they can change the variable value
14th Dec 2018, 1:51 AM
Emerson Prado
Emerson Prado - avatar