What kind of pointer is that?

Asked

Viewed 42 times

0

I have the Following Code:

int main() {
    string animal = "cabrito";
    string &pn = animal;
    
    pn = "bode";
    
    cout << animal << endl;
    
    
    return 0;
}

That generates the output:

goat

I was very confused by this code, the address of Pn receives the variable animal and manages to modify it as if it were a pointer, How so?

I also have this code that converts a string to uppercase:

int main() {
    string animal = "cabrito";
    
    for (auto &letra: animal) letra = toupper(letra);
    
    
    cout << animal << endl;
    
    
    return 0;
}

With the exit:

KID

Basically as in the first code only that changes character by character of the string, I tried to do this but this time with a pointer and it was like this:

int main() {
    string animal = "cabrito";
    
    for (auto *letra: &animal) *letra = toupper(*letra);
    
    
    cout << animal << endl;
    
    
    return 0;
}

I did it in several other ways using the Pointer but none worked.

After all that code:

string &pn = animal;
pn = "cabrito";

Are you doing?

1 answer

2


The code:

string &pn = animal;
pn = "cabrito";

It’s not necessarily a pointer of the shape you normally know in C (I recommend you read on references in C++). That is a reference. Note that the "&" is on the LEFT side of the variable declaration and not on the right side as we do on pointers to rescue your address in memory:

std::string *pn = &animal;

As much as a pointer is also a reference, this syntax is a way to "name" the reference rather than having to use a pointer:

With a pointer we’d do:

std::string *pn = &animal;
std::cout << *pn << std::endl;

With a reference:

std::string &pn = animal;
std::cout << pn << std::endl;

But it’s still the same memory region. That’s why in your first code:

int main() {
    string animal = "cabrito";
    string &pn = animal;
    
    pn = "bode";
    
    cout << animal << endl;
    
    
    return 0;
}

Resulted in "bode". The &pn is a reference to the variable animal, so its value has been changed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.