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

Time:11-03

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

CodePudding user response:

In this declaration of the array

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

the initializers are copied to elements of the array,

So the strings used as initializers and strings stored in the array are different objects.

You could declare an array of the type std::reference_wrapper as for example

#include <utility>
#include <string>

//...

std::reference_wrapper<std::string> letters[] = { std::ref( x ), std::ref( y ), std::ref( z ) };

Here is a demonstration program.

#include <iostream>
#include <string>
#include <utility>

int main( int argc, char * argv[] )
{
    std::string x = "x";
    std::string y = "y";
    std::string z = "z";

    std::reference_wrapper<std::string> letters[] =
    {
        std::ref( x ), std::ref( y ), std::ref( z )
    };

    for (const auto &r : letters)
    {
        std::cout << r.get() << ' ';
    }
    std::cout << '\n';

    x = "u";
    y = "v";
    z = "w";

    for (const auto &r : letters)
    {
        std::cout << r.get() << ' ';
    }
    std::cout << '\n';
}

The program output is

x y z
u v w

CodePudding user response:

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 };
  • Related