My issue is the following: I am making a pointer to a dynamic two dimensional array on the heap. This is done in a subfunction “Production” which fills in the elements of the table (array) and returns the pointer of the array to the main(). There I want to give the pointer as a parameter for another function “PrintTable”; which cout’s the table. My issue is that the returned pointer is actually a one dimensional array (c++) and I don’t know how to adress it to get the second row of the array..
Let me try to explain it to you:
So first I have a function which returns a pointer to a two-dimensional array.
int* Production(int num1, string name1[], int num2, string name2[])
{
int** productionTable=new int*[num1];
for (int i = 0; i < num1; i++)
{
productionTable[i] = new int[num2];
}
for (int i=0;i<num1;i++)
{
cout << "\nGive production " << name1[i]<<endl;
for (int j=0;j<num2;j++)
{
cout << "On " << name2[j] << " : ";
cin >> productionTable[i][j];
}
}
return* productionTable;
}
in the main () I let the returned pointer point to a pointer productiontable so it exists in the main.
int* productionTable=Production(num1, name1[], num2, name2[])
Then I call function printTable() witch has to output the 2dimensional array as a table. so I want to use this pointer as an argument for another function; to cout the elements from this array.
PrintTable(num1, name1[], num2, name2[], productionTable);
This function looks like this:
void printTable(int num1, string name1[], int num2, string name2[],int* productionTable)
{
cout << left <<setw(10)<< "";
for (int i=0;i<num2;i++)
{
cout << left <<setw(10)<< name2[i];
}
cout<<endl;
for (int i=0;i<num1;i++)
{
cout << setw(10)<<name1[i]<<"";
for (int j=0;j<num2;j++)
{
cout << left <<setw(10)<< productionTable[i+j];
}cout<<endl;
}
}
My problem is that I can’t get the function to output the second row right. How should i adress the second parameter of the array. So far i’ve read i should make the table point to [COLindex * COL_size + ROWindex]. I’ve tried it but i dan’t get him to print the second row. What should the COL_size paramter be?
This is your problem:
Basically, by the return, you return only the first row (or a pointer to it) discarding the rest of the table. To make it work, you could declare
ProductionandproductionTable(at all places) asint**,return productionTableinProductionand useproductionTable[i][j]for element retrieval.