c++ - How to return a 2d array where one dimension is of unknown size? -


this related this question. have function void doconfig(mappings, int& numofmappings) , i'm not sure how declare mappings. 2 dimensional array elements chars. first dimension determined @ run time, , computed in body of function. second dimension going 2. code this? i'd imagine char** mappings or that. in c++ arrays passed reference right? don't need use & though intend use value when function returns?

edit: want return this char (*mapping)[2] = new char[numofmappings][2];

as per 2to1mux's suggestion still cannot work. array appears getting right values going wrong when doconfig() function returns.

int main() {     int numofmappings = 0;     char **mappings;     doconfig(mappings, numofmappings);     cout << "this mappings" << mappings << endl;//this address different 1 given in doconfig(), wrong?     cout << "this numofmappings: " << numofmappings << endl;     cout << mappings[0][0] << "->" << mappings[0][1] << endl;//program crashes here     //code removed     return exit_success; }  void doconfig(char **mappings, int& numofmappings) {     //code removed, numofmappings calculated     for(int j = 0; j < numofmappings; j++)     {         getline(settingsfile, setting);         mappings[j] = new char[2];         mappings[j][0] = setting.at(0);         mappings[j][1] = setting.at(2);     }     for(int j = 0; j < numofmappings; j++)         cout << mappings[j][0] << "->" << mappings[j][1] << endl;//everything expected array created ok     cout << "this mappings" << mappings << endl;//different address 1 give in main } 

ok got working haking around. people please explain there solutions how known when use * , &?

since tagged question c++, not c, guess might want proper solution.

template<typename t> using vectorof2d = std::vector<std::array<t, 2>>;  vectorof2d<char> getmappings() {     return /* whatever fill */;     // (most probably) using nrvo ellide copy } 

and if afraid access might complicated:

auto mappings = getmappings();  functiontakingamapping(mappings[i]); char element = mappings[0][1]; 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -