pointer argument receiving address in c++? -


int y=5; int *yptr = nullptr; yptr = &y; 

i understand pointer stores address of y. , calling *yptr dereferences y.

if have call void function:

int main() {     int number = 5;     function( &number ); }  void function( int *nptr) {     *nptr = *nptr * *nptr; } 

if function takes pointer argument, how can call function use address? understand nptr stores addresses why couldn't defined as.

void functions (int &ref) {     ref = ref * ref; } 

my main question be: why function receiving address argument need pointer parameter receive address?

by using pass-by-reference parameter, force function not copy value of parameter itself, instead, use actual variable provide. so, more clear view, see below:

void function( int number ) {   cout << number; }  function( myint ); // function copy myint, local variables stack 

but, using pass-by-reference method, this:

void function ( int & number ) {   cout << number }  function( myint ); // function not copy myint local variables stack, instead, use existent myint variable. 

there no difference in how compiler work pass-by-pointer , pass-by-reference parameters. instead, call of function so:

void function_p( int *number ) {   cout << *number; }  void function_r( int & number ) {   cout << number; }  // , calls  function_p( &myint ); // required use address-of operator here function_r( myint ); // effect same, less effort in writing address-of operator 

in c++11, programmers started use pass-by-reference method, in general, ordinarily because has easier writing "template".


to complete answer question, * , & operators refer type of parameter, create compound types. compound type type defined in terms of type. c++ has several compound types, 2 of references , pointers.

you can understand affect type of variable (in our case, parameter), writing them in proper way:

int* p1; // read this: pointer p1 points int int* p2 = &var1; // read this: pointer p2 points int variable var1  int var1 = 12; int& ref1 = var1; // , read this: ref1 reference var1 

you can consider references represent different same block of memory.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -