How to (set size or resize) and fill: Two dimensional string array inside a function?

Hi I need to make a function that modify and write, a two dimensional string array
passed as an argument.

The two dimensional array size will be set inside that function.
or it can be...
The two dimensional array size will be redimensioned inside that function.

I was researching, and probably I should use memory allocation, use references to a triple pointer. But Im a bit confusing, if anyone helps. Thanks in advance

This is what Ive done so far...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
   void func_str(string ***M, int &rows, int &cols ) {
   // rows and cols will be known here
   rows = 2;
   cols = 5;

   // set memory allocation
   *M = (string**)malloc(5*sizeof(string*));
   (*M)[0] = (string*) malloc(5*sizeof(string));
   (*M)[1] = (string*) malloc(5*sizeof(string));


   // trying to assign values to M[0][0], M[0][1]...
   static string A[5] = {"aaa1","bbb1","ccc1","ddd1","eee1"};
   memcpy((*M)[0], A, 5*sizeof(string));

   A[0] = "aaa2";
   A[1] = "bbb2";
   A[2] = "ccc2";
   A[3] = "ddd2";
   A[4] = "eee2";
   memcpy((*M)[1], A, 5*sizeof(string));
}

main () {
   string  **M;
   int rows, cols;
   func_str(&M, rows, cols);
   return 0;
}

Last edited on
1. Use vector<vector<string>> if you want an easy life and avoid the pain of roll your own memory management.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void myfunc( vector<vector<string>> &result, int &rows, int &cols ) {
    rows = 2;
    cols = 5;
    result.resize(rows);
    for ( int r = 0 ; r < rows ; r++ ) {
        result[r].resize(cols);
    }
    static string A[5] = {"aaa1","bbb1","ccc1","ddd1","eee1"};
    for ( int r = 0 ; r < rows ; r++ ) {
        for ( int c = 0 ; c < cols ; c++ ) {
            result[r][c] = A[c];
        }
    }
}

int main ( ) {
    vector<vector<string>> result;
    int rows, cols;
    myfunc(result,rows,cols);
    cout << "Rows=" << rows << endl;
    cout << "Cols=" << cols << endl;
    cout << result[0][0] << endl;
}

$ g++ -std=c++11 foo.cpp
$ ./a.out 
Rows=2
Cols=5
aaa1


2. If you don't want to use vectors, then you MUST use new instead of malloc, to ensure that constructors for you strings are called. Further, you must use assignment (not memcpy) to copy the strings into your array.

@salem c (293) thank you very much!
it works perfectly, and very profit answer. And not neccesary to use statics.
Topic archived. No new replies allowed.