0

Why can't I see output value of smartPtr2D from this code?

shared_ptr<shared_ptr<int[3]>[5]> smartPtr2D;
for (int i = 0; i<3; i++)
{
    for (int j = 0; j<5; j++)
    {
        smartPtr2D[i][j] = 11;
    }
}

for (int i = 0; i<3; i++)
{
    for (int j = 0; j<5; j++)
    {
        cout << "value:" << smartPtr2D[i][j] << endl;
    }
}
Adil B
  • 14,635
  • 11
  • 60
  • 78
  • `std::shared_ptr` behaves like a pointer and it doesn't point to anything, so dereferencing it will be undefined behavior. You need something like `smartPtr2D = std::make_shared>();` and then you need to allocate memory for the inner `shared_ptr`s too. – nwp Nov 14 '17 at 15:24
  • You should consider using a wrapper around a flat array instead of combining pointers like that. – nwp Nov 14 '17 at 15:25
  • @nwp can you please, write some simple sample with smart pointers 2d array. – Martin Boryczko Nov 14 '17 at 15:45
  • I did above in the comment. You just have to do it again for the other pointers. – nwp Nov 14 '17 at 15:50
  • Also note that this isn't what people normally think of as a 2d array. 2d arrays are thought of as contiguous. Your structure is more like an array of pointers to arrays, which is not quite the same thing. – nwp Nov 14 '17 at 16:00
  • Thank You very much, because I see now that I don't have basic understanding of smart pointers. It looks like different to code writing before modern Cpp. – Martin Boryczko Nov 14 '17 at 16:25
  • Consider [getting a book](https://stackoverflow.com/a/388282/3484570). [The tour](http://www.stroustrup.com/Tour.html) is intended for people who know programming and some older C++ and just need to be brought up to speed with the modern part. – nwp Nov 14 '17 at 16:27

0 Answers0