I have a method that receives a char ** as an argument in order to parse and construct a proper inner object.
void build (const char* values[], const int amount=3)
{
//..parse values and create instance of an inner field..
}
It is constant, because I just want to use those values and I don’t need to modify them at all. This works pretty much fine.
Now I want to be able to code a method that returns to me a const char ** in a way that I am able to use this returned value in the previously declared method. At first, I got the values needed from the instance of my class, converted them to string and put them in an array and returned it, but it was complaining that I was returning a pointer to a local variable. So I thought of using another field to hold this pointer, I created char ** values. Then I realized that I would need to allocate the memory for the value it points to, so I went trough with it. Currently the method I’m describing looks something like:
const char** getValues()
{
string var;
var = toString(point.zone);
values[0]= new char[var.length()+1]();
strcpy(values[0], var.c_str());
var = toString(point.easting);
values[1]= new char[var.length()+1]();
strcpy(values[1],var.c_str());
var = toString(point.northing);
values[2]= new char[var.length()+1]();
strcpy(values[2],var.c_str());
return values;
}
But at the moment this will complain because char ** values is not constant. But if I make it constant,the strcpy will complain about the opposite. If I dont return it constant then I cant us it in other function. I need help fixing this problem. Any help is deeply appreciated, thanks.
You got a compilation error because you try to strcpy to a
char const*directly.You should instead strcpy to a
char *and assign this pointer back to the values[].See the modified code below for a simple solution: