Ishk
Ishk

Reputation: 21

How to create and store string data in multidimensional array?

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"};

Upvotes: 0

Views: 74

Answers (3)

Lyubomir Vasilev
Lyubomir Vasilev

Reputation: 3030

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;

Upvotes: 1

TeRRy
TeRRy

Reputation: 11

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';

}

Upvotes: 0

Talal02
Talal02

Reputation: 172

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...

Upvotes: 0

Related Questions