I need to populate a vector variable from a char** variable that i get from another function.
I tried on my own the following program:
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
char** getS();
int main()
{
int i;
vector<string> a;
cout << "Hello World" << endl;
char** b=getS();
char c[][5] = {"one","two","thr"};
//a.insert(a.begin(), b, b+3);
for(i=0;i<3; i++)
{
a.push_back(b[i]);
}
for(i=0;i<3; i++)
free(b[i] );
free(b);
for(i=0;i<3; i++)
{
cout <<a[i].c_str() << endl;
}
return 0;
}
char** getS()
{
char** list;
int number_of_row=3,number_of_col =5,i;
list = (char**)malloc(sizeof(char*)*number_of_row);
for(i=0;i<number_of_row; i++)
{
list[i] =(char*) malloc(sizeof(char)*number_of_col);
list[i] ="Hello";
}
return list;
}
I tried executing it in the this site.
I am getting an invalid pointer error and a dump in console. But I believed pointers can be freed as i did above after pushing the values into a vector. If i remove the freeing of pointer b then the code works fine.
I need to use this vector after freeing the original char** variable from which it was populated.
length of the string array in char** is hardcoded in my example.