Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can there be an array made out of strings pointing to the same Memory Adress

I have 3 strings. I need to create an array out of those 3 strings, when I do it, it gets shown to me that the memory adresses of the strings are different than the ones of the array. Meaning that they dont point to the same thing. But I want that if I change the strings out of which I made the array, after the array creation, that the array will automatically update. And vice-versa.
Is this possible and how can I do this.
This is my code to show that they dont use the same Memory adresses, hence, they arent the same:

    std::string x = "x";
    std::string y = "y";
    std::string z = "z";

    std::string letters[3] = {x, y, z};

    std::cout << &x << "\t" << &y << "\t" << &z << "\n";
    std::cout << &letters[0] << "\t" << &letters[1] << "\t" << &letters[2] << "\n";

The output is:

0x20b1bff730    0x20b1bff710    0x20b1bff6f0
0x20b1bff690    0x20b1bff6b0    0x20b1bff6d0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

So here some code using pointers, that does what you want

std::string* xp = new std::string("x");
std::string* yp = new std::string("y");
std::string* zp = new std::string("z");

std::string* letters[3] = { xp, yp, zp };

*xp = "X"; // changes *xp and *letters[0], since xp == letters[0]

Now raw pointers are a bad idea, so the above should be written using smart pointers

#include <memory>

std::shared_ptr<std::string> xp = std::make_shared<std::string>("x");
std::shared_ptr<std::string> yp = std::make_shared<std::string>("y");
std::shared_ptr<std::string> zp = std::make_shared<std::string>("z");

std::shared_ptr<std::string> letters[3] = { xp, yp, zp };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading