This is related to this question. I have a function void doConfig(mappings, int& numOfMappings)
and I'm not sure how to declare mappings. It is a two dimensional array whose elements are chars. The first dimension is determined at run time, and will be computed in the body of the function. The second dimension is always going to be 2. What is the code for this? I'd imagine it to be char** mappings
or something like that. Also in C++ arrays are always passed by reference right? So I don't need to use &
even though I intend to use the value when the function returns?
EDIT: Basically I want to return this char (*mapping)[2] = new char[numOfMappings][2];
as per 2to1mux's suggestion I still cannot get it to work. The array appears to getting the right values but something is going wrong when the doConfig()
function returns.
int main()
{
int numOfMappings = 0;
char **mappings;
doConfig(mappings, numOfMappings);
cout << "This is mappings" << mappings << endl;//this address is different than the one given in doConfig(), is that wrong?
cout << "this is 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 is as expected so array created ok
cout << "This is mappings" << mappings << endl;//different address than the one give in main
}
OK I got it working now but mainly from haking around. Could people please explain there solutions as to how they known when to use *
and &
?