function - Pointer Confusion with C++ -


i confused c++ pointers , reference operators. main confusion following (simple ) code:

#include <iostream>  using namespace std;  void changeint(int &a) {     *= 3; }  int main() {     int n = 3;     changeint(n);     cout << n << endl;       return 0; } 

mainly, confused why changing address (&a) changes actual variable (n). when first attempted problem code:

#include <iostream>  using namespace std;  void changeint(int &a) {     *a *= 3; }  int main() {     int n = 3;     changeint(n);     cout << n << endl;       return 0; } 

but gives me error. why when change address changes variable, when change value pointed address error?

your second example not valid c++, can dereference pointer (or object type overload operator*, not case).

your first example pass parameter reference (int &a not "the address of a", reference a), why change a change object being passed function (in case, n)


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -