Please explain how it's output is 100? #include <iostream> using namespace std; void myFunc(int *x) { *x = 100; } int main() { int var = 20; myFunc(&var); cout << var; } | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 2

Please explain how it's output is 100? #include <iostream> using namespace std; void myFunc(int *x) { *x = 100; } int main() { int var = 20; myFunc(&var); cout << var; }

16th Jul 2016, 7:37 AM
yashmi
5 ответов
+ 4
Actually any changes to x itself is dereferencing. But *x receives values for var. add "cout <<x;" in myFunc after *x = 100 and add "cout <<&var" in main after calling myFunc both will give you the same address.
16th Jul 2016, 10:23 AM
Dhinakaran Purushothaman
+ 2
The myFunc receives address of var in pointer x. So, x is nothing but a pointer to var. Thus, whatever value assigned to printer's content is directly assigned to var. I hope you understand the concept of pointers.
16th Jul 2016, 8:10 AM
Dhinakaran Purushothaman
+ 2
*(& var) is var
18th Jul 2016, 8:46 AM
Kovoor Prajwal
Kovoor Prajwal - avatar
+ 1
consider, let address of var be 0x2345. in myFunc(&var) yu are sending address of var,ie. address of 20. which can be written for understanding purpose as myFunc(address of value 20),ie myFunc(0x2345). so in function body, since yu have sent address any change made to X changes its value. ie (int *x) takes address 0x2345. now in the body.. yu have derefrenced the pointer.so it says "value@0x2345"=100. it overwrites before-value 20 to after-value 100.since yu have made changes directly through address.. "count<<var" gives O/p as 100..
17th Jul 2016, 10:34 AM
Rudra Gowda
Rudra Gowda - avatar
0
*x=100 doesn't do the dereferencing?
16th Jul 2016, 8:15 AM
yashmi