Why will deleting 2D array in this way fail (C++)? -
in following codes try build 2d array c++, when run program fails.
#include <iostream> #include <vector> using namespace std; int obtain_options( char ** optionline) { vector< char*> options; options.push_back("abc"); options.push_back("def"); std::copy(options.begin(), options.end(), const_cast< char**>(optionline)); return options.size(); } int main(int ac, char* av[]) { char** optionline; int len; optionline = new char* [2]; (int i= 0; i<2; i++) { optionline[i] = new char [200]; } obtain_options(optionline); (int i=0; i<2; i++) { cout<<optionline[i]<<endl; } (int i=0; i<2; i++) delete [] (optionline[i]); delete []optionline; return 0; }
i understand there problems allocating memory optionline in function obtain_options(), , if change obtain_options() in way, work:
int obtain_options( char ** optionline) { vector< char*> options; char *t1 = new char [100]; t1[0] = 'a'; t1[1] = 'b'; t1[2] = 'c'; t1[3] = '/0'; options.push_back(t1); char *t2 = new char [100]; t2[0] = 'd'; t2[1] = 'e'; t2[2] = 'f'; t2[3] = '/0'; options.push_back(t2); std::copy(options.begin(), options.end(), const_cast< char**>(optionline)); return options.size(); }
my question if not change obtain_options(), how delete 2d array optionline in proper way.
your vector contains set of character pointers. but, actual memory pointed these strings not continuous expect them be. so, call not work expect.
std::copy(options.begin(), options.end(), const_cast< char**>(optionline));
in worst case this, now.
for (int i= 0; i<2; i++) { strcpy(optionline[i],options[i]); }
but avoid these memory handling unless learning pointers , allocations.
see how neat can code in c++:
int obtain_options( vector<string>& anoptions_out) { anoptions_out.push_back("abc"); anoptions_out.push_back("def"); return anoptions_out.size(); } int main(int ac, char* av[]) { vector<string> anoptions; obtain_options( anoptions ); (int i=0; i<anoptions.size(); i++) { cout<< anoptions[i].c_str() <<endl; } return 0; }
no allocations/deallocations yourself.
Comments
Post a Comment