0

How can I create and store string data in a multidimensional array using pointers? My attempt is:

// I declaring row 3 and column 2 
string** arr = new string*[3][2]; // I am having issue in here

// I am trying to add data
arr[0] = {"first", "second"};
4
  • Use std::array<std::arrayr<std::string,2>,3> arr; Commented Oct 30, 2020 at 5:23
  • You need to initialise every element with new string() Commented Oct 30, 2020 at 6:32
  • Any number of examples on the internet of how to allocate multidimensional arrays. The good ones don't use pointers, but I'm sure you can find those as well. Commented Oct 30, 2020 at 6:48
  • @AlanBirtles, would you mind to show me the example? Commented Oct 30, 2020 at 6:49

3 Answers 3

1

If you want to be able to initialize a whole sub-array like that with {"first", "second"}, you most likely would need to use a std::vector or std::array instead of manually allocating the memory for the array. Unless you have very specific reasons for using pointers, here is how it could look with vectors:

using str_vec = std::vector<std::string>;
std::vector<str_vec> v(3, str_vec(2, ""));

v[0] = {"first", "second"};

But if you really need pointers, then you'll have to first allocate the memory for the "row" and then do separate allocations for each "column":

std::string** a = new std::string*[3]; 
for(int i = 0; i < 3; ++i) {
    a[i] = new std::string[2];
}

After which you can fill the values one by one:

a[0][0] = "first";
a[0][1] = "second";

And don't forget about deleting all these arrays after you are done. In the reverse order, you first need to delete all columns and then the "row":

for(int i = 0; i < 3; ++i) {
    delete[] a[i];
}
delete[] a;
Sign up to request clarification or add additional context in comments.

Comments

0

There is mistake in the first line of initialization. Initialize it like this if you want to avoid any error.

string** arr = new string*[3]; 
/* It will have count of rows of string you will have like in this statement 3 rows of string. */
// Now you will have to tell about columns for each row separately.

for(int i = 0; i < 3; i++) {
    arr[i] = new string[2]; // Here you are initializing each row has 2 columns
}

// Now write your code below...

Comments

0

you can rewrite yours code as following :

string **arr = new string*[3]; // row 3

for(unsigned i = 0; i < 3; i++)
    arr[i] = new string[2]();  // column 2

arr[0][0] = "first"; arr[0][1] = "second";

for(unsigned i = 0; i < 3; i++){. // yours ans
    for(unsigned j = 0; j < 2; j++)
        cout << arr[i][j] << " ";
    cout << '\n';

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.