In the following codes I try to build a 2D array with c++, but when I run this program it 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];
for (int i= 0; i<2; i++)
{
optionLine[i] = new char [200];
}
obtain_options(optionLine);
for (int i=0; i<2; i++)
{
cout<<optionLine[i]<<endl;
}
for (int i=0; i<2; i++)
delete [] (optionLine[i]);
delete []optionLine;
return 0;
}
I understand there are some problems with allocating memory to optionLine in function obtain_options(), and if I change obtain_options() in this way, it will 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 is if I do not change obtain_options(), how could I delete the 2D array optionLine in a proper way.
your vector contains a set of character pointers. But, the actual memory pointed to by these strings are not continuous as you expect them to be. So, this call will not work as you expect.
In worst case you could do like this, which is what you almost do yourself now.
But avoid all these memory handling unless you are learning the pointers and allocations.
See how neat you can code this like this in C++:
No allocations/deallocations by yourself.