Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer address as reference in function

I've got one general question, why can't I pass the the pointer's address as a reference?

void domdom(string &foo)
{
 foo = "";
}

string fooso = "blabal";
string* p_fooso = fooso;

domdom(p_fooso); // <-- why is that not possible? And what should I pass to be able to modify foosoo?

I know I could change the function domdom to accept (string* foo), but is it also possible to modify the string fooso in the function by using the pointer to it and the given function?

like image 483
Ammy Avatar asked Apr 13 '26 18:04

Ammy


2 Answers

why can't i pass the the pointer's address as a reference?

Because that's how the language is defined.

Instead, you can dereference the pointer to get a reference to the string:

domdom(*p_fooso);

or, pass the actual object directly:

domdom(fooso);

Also note that string* p_fooso = fooso; doesn't compile. You have to write string* p_fooso = &fooso;.

like image 60
emlai Avatar answered Apr 15 '26 06:04

emlai


Just declare p_fooso as a string reference type. You might want to rename variable as r_fooso!

string& r_fooso=fooso;
like image 23
varun Avatar answered Apr 15 '26 08:04

varun



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!