Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer argument receiving address in c++?

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

I understand that the pointer stores the address of y. and calling *yPtr dereferences y.

If I have a call to the void function:

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

void function( int *nPtr)
{
    *nPtr = *nPtr * *nPtr;
}

if the function takes a pointer as argument, how can the call to the function use an address? I understand that nPtr stores addresses but why couldn't it be defined as.

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

My main question would be: Why does a function receiving an address argument need a pointer parameter to receive the address?

like image 524
user3348712 Avatar asked May 19 '26 07:05

user3348712


1 Answers

By using a pass-by-reference parameter, you force your function not the copy the value of the parameter itself, instead, to use the actual variable you provide. So, for a more clear view, see below:

void function( int number )
{
  cout << number;
}

function( myInt ); // function will copy myInt, into its local variables stack

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

void function ( int & number )
{
  cout << number
}

function( myInt ); // function will not copy myInt into its local variables stack, instead, it will use the already existent myInt variable.

There is no difference in how to compiler will work with pass-by-pointer and pass-by-reference parameters. Instead, the call of your function will look like so:

void function_p( int *number )
{
  cout << *number;
}

void function_r( int & number )
{
  cout << number;
}

// and the calls

function_p( &myInt ); // it is required to use address-of operator here
function_r( myInt ); // the effect will be the same, but with less effort in writing that address-of operator

In C++11, programmers started to use pass-by-reference method, in general, ordinarily because it has an easier writing "template".


To complete the answer to your question, the * and & operators refer only to the type of the parameter, so that they create compound types. A compound type is a type that is defined in terms of another type. C++ has several compound types, two of which are references and pointers.

You can understand that they only affect the type of a variable (in our case, a parameter), by writing them in a proper way:

int* p1; // we will read this: pointer p1 points to an int
int* p2 = &var1; // we read this: pointer p2 points to int variable var1

int var1 = 12;
int& ref1 = var1; // and we read this: ref1 is a reference to var1

You can generally consider references represent a different for the same block of memory.

like image 137
Victor Avatar answered May 20 '26 20:05

Victor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!