Passing an array by reference using pointers in C++ - c++

In some new territory working with pointers and references, I am attempting to pass an array by reference into a function using a pointer, however I keep getting errors no matter what I try, I am sure the problem is very simple to fix but I just cant seem to wrap my head around it, can anyone see the mistake im making? any help will go a long way thanks
#include<iostream>
#include<cmath>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <new>
using namespace std;
//Inline function
inline double getFahrenheit(double theCelsius)
{
//Convert the celcius to farenheit
return (theCelsius + 32) * 5 / 9;
}
void outputWeather(double *temperaturesArray, const string WEEK_DAY_NAMES[], const double MAX_NUMBER)
{
//this is a counter that will increment through the days and various
int counter;
//reset the counter to 0 so we can use it again
counter = 0;
//print a header
cout << "THIS WEEKS TEMPERATURE REPORT " << endl;
//print a divider
cout << "=============================" << endl;
//while the counter is less than 7 repeat again
while(counter < MAX_NUMBER)
{
//print out the temperatures by day
cout << WEEK_DAY_NAMES[counter] << " " << temperaturesArray[counter] << "\370C " << getFahrenheit(temperaturesArray[counter]) <<"\370F "<< endl;
//increase the counter by 1
counter +=1;
}
}
//Function that will determine whether or not the value the user entered was numeric and within the range
double checkValidation(string weekDay)
{
//Create a variable to store a valid number
double validNumber;
//This will hold the value for the lowest
const double MIN_NUMBER = 1;
//This will hold the value for the highest temperature
const double MAX_NUMBER = 365;
//This will hold the value for the valid number that the user will eventually enter
validNumber = 0.0;
//This will alert the user to enter a temperature for that day of the week
cout << "Please enter the temperature for " << weekDay << endl;
//This will take in teh value the user entered for teh temperature
cin >> validNumber;
//If the text the user entered was not numeric start again
if(cin.fail())
{
//C++ built in methods for clearing the cin
cin.clear();
fflush(stdin);
//alert the user what they typed was wrong
cout << "invalid input. please try again and enter a numeric value" << endl;
//pass in the weekeday and start over
checkValidation(weekDay);
}
else
{
//if teh number falls outside the range
if(validNumber < MIN_NUMBER || validNumber > MAX_NUMBER)
{
//Alert the user that it was outside the range
cout << "invalid input. please try again and enter a value between -90 and 60" << endl;
//pass in the weekday and try again
checkValidation(weekDay);
}
}
//return the valid number
return validNumber;
}
int main()
{
//this is a counter that will increment through the days and various
int counter;
//a constant to hold the variable for the number of days
const int MAX_COUNTER = 7;
//an array that will hold all the days of the week
const string WEEK_DAY_NAMES[] =
{
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
};
//this will hold all of teh temperatures
double temperaturesArray[MAX_COUNTER];
//start the counter off at 0
counter = 0;
//begin telling the user to enter temperatures by printing a header
cout << "Please enter the temperature for every day of the week " << endl;
//while the counter is less than 7 we will repeat
while(counter < MAX_COUNTER)
{
//add temperature to the array
temperaturesArray[counter] = checkValidation(WEEK_DAY_NAMES[counter]);
//add 1 to the counter
counter +=1;
}
double * arrayPointer = new double[MAX_COUNTER];
arrayPointer = &temperaturesArray;
outputWeather(arrayPointer, WEEK_DAY_NAMES, MAX_COUNTER);
system("PAUSE");
return 0;
}

In C++, the size of an array is encoded into its type.
There is no general "array of doubles" type. But there is an "array of 7 doubles" type, and an "array of 13 doubles" type, and so on.
So to pass an array as an array, and not simply as a pointer, to a function, you need to encode the precise type in the function's signature.
It won't be "a function which takes an array", but "a function which takes an array of size 7".
The way to do that is as follows:
void f(double (&arr)[7]);
Or of course, you can template it, if the array size is not fixed:
template <size_t N>
void f(double (&arr)[N]);
But really, what you're trying to do shouldn't be done using raw arrays at all.
Use the standard library vector.

Briefly, replacing line
arrayPointer = &temperaturesArray;
with
arrayPointer = temperaturesArray;
makes the code to compile.
Notice that arrayPointer is of type double* and temperaturesArray is of type double[MAX_COUNTER] (with MAX_COUNTER = 7). Hence, you can assign arrayPointer to the address of a double but you cannot assign arrayPointer to the address of a double[MAX_COUNTER]. That's what the original code attempted to do and thus, it failed to compile.
On the other hand, each element of a double[MAX_COUNTER] is a double. In particular, the first element is a double and you can assign its address to arrayPointer:
arrayPointer = &temperaturesArray[0];
The fix above is just a synctatic sugar for this line. Indeed, when you assign an object of type "array of type T" (e.g. double[MAX_COUNTER]) to a "pointer of type T", then the compiler performs the so called array-to-pointer conversion which means that is assigns the address of the first array element to the pointer.
Now a little remark on your code (with the provided fix), specifically, the following lines:
double * arrayPointer = new double[MAX_COUNTER];
arrayPointer = temperaturesArray;
The first line above allocates heap memory to store an array of MAX_COUNTER objects of type double. Then the address of the first element of this array is assigned to arrayPointer.
Then, the following line reassigns arrayPointer to the address of the first element of temperaturesArray. Therefore, the address of the first element of the heap allocated array is lost and you can no longer delete it. Remeber that every call to new must be matched by a call to delete (otherwise you have a memory leak). In this particular case, however, the best thing to do isn't call delete. Actually, you should eliminate the call to new since the heap memory is never used. More precisely, you can remove the first line above.

Related

Why does assigning a value to a string in a struct crash the program?

I have commented out the problematic string, attempted to pass the input to a string that is not a member of the struct, then passing it to the correct string, to no avail. To achieve the intended function, the string must go through this struct. Where is it going wrong?
Structure code:
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
class passingdata
{
public:
passingdata()
{
//constructor
};
~passingdata()
{
//destructor
};
int convertedResponse;
const string headers[4] = {"Labor/Materials", "Cost (per unit)", "Total Units", "Total Cost"}; //this is all to be written to a file later.
struct dynInputs
{
string name;
int perCost;
int unitTotal;
int totalCost = perCost * unitTotal;
};
void acceptInputs()
{
string name = "";
string response = "";
const string positiveResponse = "yes";
cout << "Would you like to insert a label?" << endl;
getline(cin, response);
if (response == positiveResponse)
{
populateSaveData();
}
else
{
//nothing yet
}
}
void populateSaveData()
{
if (convertedResponse = 1)
{
cout << "How many labels would you like to create?" << endl;
int labelCount;
cin >> labelCount;
cin.clear();
int labelsNeeded = labelCount;
dynInputs* dynamicInputs;
dynamicInputs = new dynInputs[labelsNeeded];
while (labelsNeeded > 0)
{
cout << "please type the name for this row" << endl;
cin.ignore();
//string tempName = "";
//getline(cin, tempName); this works!
getline(cin, dynamicInputs[labelsNeeded].name); //this breaks, goes to trash memory when done this way
system("pause");
cin.clear();
//tempName = dynamicInputs[labelsNeeded].name; breaks as well
cout << dynamicInputs[labelsNeeded].name << endl;
//cout << tempName << endl;
system("pause");
cout << "please type the cost of the unit, and the number of units" << endl;
cin >> dynamicInputs[labelsNeeded].perCost;
cin.clear();
cin >> dynamicInputs[labelsNeeded].unitTotal;
cin.clear();
labelsNeeded--;
}
cout << dynamicInputs[0].unitTotal << endl;
The dynamicInputs[labelsNeeded] array points to junk memory, yet I'm unsure of why it only crashes assigning value to the string.
In labelsNeeded you store the size of the array.
Then in the first iteration you use labelsNeeded to index into your array. Since C++ indexes an array starting from 0, the largest possible valid index is (the size of the array) - 1.
Eg.: For an array of size 4, your valid index range is [0, 1, 2, 3].
Now what you are doing is setting labelsNeeded to equal labelCount and then allocate an array of the size equalig labelsNeeded. And then in the first iteration you use the value of labelsNeeded as an index with this original value for accessing an element in your array. Which goes past the valid range of your array. Hence the program crashes.
I see that at the and of the iteration you decrement labelsNeeded but that is too late considering that you already tried to use the original value earlier in the code.
Your labelsNeeded > 0 condition for your while loop is also incorrect if you are using this "decrement the index at the end of the iteration" solution since it will fail to write the first (at index 0) element of your array.
Try moving the labelsNeeded-- line to the beginning of the iteration.
Note:
As to "why it only crashes assigning value to the string".
C++ (or rather the runtime) does not care whether your pointer points to a valid address or not. Simply because a pointer is just a memory address. By it self it is just a number stored in memory. A pointer that references invalid memory will only crash your program (or do other weird stuff) if you want to dereference it or in other words -> If you want to actually use the pointer to access that place in memory. It is not the "invalid" memory address in the pointer that crashes but the act of trying to access the memory at that address. The distinction may look subtle but is very important nonetheless. You can have any number of "null pointers" in the program as long as you don't try to dereference null.
Note 2:
Yours is an especially interesting mode of failure since it can fail in one of two places:
Since you are indexing an element that is one past the end of the array, that may as well coincide with the end of the heap that was assigned to the program. So it may crash there. But... Most likely your array is not allocated in such a place and there will still be accessible heap past the end of your array so dereferencing one element past your array may as well give you "something" and by something I mean some memory content cast to the type that you have. But of course from your point of view that is some random data.
If execution survived the previous section and now you have a struct with random data, you also have your string in your struct that is also filled with random garbage. Which means its pointer to the actual string content is also random (most likely pointing somewhere before or past your addressable space) as well as its size and other state information also being garbage. So if you reassign that string then its original content pointer will likely be accessed (eg.: deallocation) which will result in a crash.

Passing and updating a structural array

So I'm having some trouble with my program. It doesn't seem to fill the array properly. It dosen't seem to populate pass element 0, even though I'm increasing i. When I debug and go back, i remains zero. Should I be doing something different? I feel like I'm passing or updating the array improperly. Can't really use any STL libraries. Thank you in advance for any help.
struct Client
{
string name;
string zip;
double balance;
};
Client bAccounts [30]; //structural array in main()
int addClnt(Client(&bAccounts)[30], int); //prototype
int addClnt(Client(&bAccounts)[30], int clientCount) //function to add
elements
{
cout << "Enter Account Name:" << endl;
cin >> bAccounts[i].name;
cout << "Enter Account Zip:" << endl;
cin >> bAccounts[i].zip;
cout << "Enter Account Balance:" << endl;
cin >> bAccounts[i].balance;
cout << "Enter Last Transaction" << endl;
cin >> bAccounts[i].lastTrans;
clientCount++; //to return number of clients added
i++; //to populate different element of array on next call of function.
return clientCount + 1;
}
So I added + 1 to return clientCount and then set i = clientCount. However, clientCount remains at zero and dosen't update.
The reason the array doesn't have any values after the first one is because you never reach passed the first element. You increment i at the end of the function, but at the top of your addClnt function, i is set back to 0 . This will just keep resulting on overwriting the old previous data
EDIT:
#include <iostream>
//use pass by reference (&)
void add_client(int& index_loc){
//do whatever
//this changes the actual value passed into the function
index_loc++;
}
int main(){
int loc = 0;
add_client(loc);
add_client(loc);
add_client(loc);
//outputs 3
std::cout << "current #: " << loc << "\n";
}
clientCount is only getting incremented in that functions scope. When that function goes to it's return statement, all variables and all the work it did has completely died.
You are passing clientCount by value and not by reference, so clientCount will always be 0, and incrementing it inside that local function won't actually change clientCount's value outside of the function.
What you need to do is pass it by reference.
EDIT: The chosen answer does not explain why his solution works. The answer provided is incorrect.
The reason why the code works because again, you pass by reference and not by value.

Write access violation - **this**

I'm trying to refactor some code to use pointers and am running into a write access violation on my function calls.
I'm making these edits because my homework project requires the usage of the -> member operator as well as constructors and destructors.
One more edit: the input file worked just fine when I was formerly working without pointers, but the moment I added pointers everything broke.
Here's my code:
In main.cpp:
#include "student.h"
int main()
{
/*
TODO:
2. Implement the class such that member pointers can be used to access the members.
3. Implement pointers that point to each of the students' test scores as well as the average test score.
*/
const int numStudents = 15; // Number of students
Student * students = new Student[numStudents]; // Dynamically allocated array of Student objects
Student ** studentsPtr = &students;
// Starting file stream for studentRecords.dat
ifstream student_records("student_records.dat");
// Error checking for file loading
if (!student_records)
{
cerr << "ERROR: The record file could not be opened for reading." << endl;
exit(1);
}
// Load data from file
string current_value;
stringstream newval;
int tempID;
string tempName;
double tempTestScore;
for (int index = 0; index < numStudents; index++)
{
// Store the student ID
getline(student_records, current_value);
newval << current_value;
newval >> tempID;
studentsPtr[index]->setID(tempID);
newval.clear();
// Store the student first name
getline(student_records, current_value);
newval << current_value;
newval >> tempName;
studentsPtr[index]->setFirstName(tempName);
newval.clear();
// Store the student last name
getline(student_records, current_value);
newval << current_value;
newval >> tempName;
studentsPtr[index]->setLastName(tempName);
newval.clear();
// Add each test score.
for (int testScoreIndex = 0; testScoreIndex < numTests; testScoreIndex++)
{
getline(student_records, current_value);
newval << current_value;
newval >> tempTestScore;
studentsPtr[index]->addTestScore(tempTestScore, testScoreIndex);
newval.clear();
}
// Calculate the student's average
students[index].calculateAverage();
}
// Print all data
for (int index = 0; index < numStudents; index++)
{
studentsPtr[index]->printAll();
}
delete[] students; // Free memory pointed to by students array
students = NULL; // Clear the memory.
system("pause");
return 0;
}
In student.h:
#pragma once
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
const int numTests = 10;
// Student class declaration
class Student
{
private:
// Student ID and name
int id;
string firstName;
string lastName;
// List of student test scores
// vector<double> testScores;
double * testScores = new double[numTests];
// Student average test score
double average;
public:
Student() // Default constructor
{
const int numTests = 10;
id = 0;
firstName = " ";
lastName = " ";
average = 0.0;
}
~Student() // Destructor
{
delete[] testScores;
}
void setID(int); // Set the student ID
void setFirstName(string); // Set the student name
void setLastName(string);
void addTestScore(double, int); // Add a test score to the vector
void calculateAverage(); // Calculate the average of all test scores
void printAll(); // Output all data to the screen for a given student
};
In student.cpp:
#include "student.h"
// setID sets the id value.
void Student::setID(int studentID)
{
id = studentID;
}
// setName sets the name value.
void Student::setFirstName(string studentFirstName)
{
firstName = studentFirstName;
}
void Student::setLastName(string studentLastName)
{
lastName = studentLastName;
}
// addTestScore adds a test score to the vector
void Student::addTestScore(double testScore, int index)
{
testScores[index] = testScore;
// testScores.push_back(testScore);
}
// calculateAverage adds every test score from the vector and divides them by the number of test scores in the list.
void Student::calculateAverage()
{
double totalScores = 0.0;
// for (double index : testScores)
for (int index = 0; index < numTests; index++)
{
totalScores += testScores[index];
}
average = totalScores / numTests;
}
// printAll prints all the data to the screen.
void Student::printAll()
{
cout << "=========================================================\n";
cout << "Student ID:\t" << id << endl;
cout << "Student Name:\t" << firstName << " " << lastName << endl;
cout << setprecision(4) << "Average:\t" << average << endl;
cout << "Test Scores: " << endl;
// Printing the test scores nicely
int scoresPerLine = 5;
for (int i = 0; i < numTests; i++)
{
cout << setprecision(4) << testScores[i] << "\t";
if ((i + 1) % scoresPerLine == 0)
{
cout << endl;
}
}
cout << endl;
cout << "=========================================================\n\n";
}
The error I'm getting is Exception thrown: write access violation. this was 0xCCCCCCCC and it throws the exception at a break point created at
void Student::setFirstName(string studentFirstName) at the line firstName = studentFirstName.
My question is: what exactly is preventing this from working? Am I doing something wrong? I dont' get any errors before I compile everything, so it looks like everything is built ok. I've also tried using a pass-by-reference on that member function, but that's also failing with the same response.
Am I doing something wrong?
Yes, definitely :)
Let's go through it:
Student * students = new Student[numStudents];
... the above allocates a dynamic array of 15 Student objects; so far, so good.
Student ** studentsPtr = &students;
This line is the source of the trouble. You've declared a double-pointer Student ** and initialized it to point to the address of the students pointer. This is legal C++, but note that there is only the standalone students pointer -- in particular, there is not an array of pointers-to-Student in your program anywhere. (There is an array of Student objects but that is not the same thing as an array of pointers-to-Student)
... then a bit later on, comes the actual trouble:
for (int index = 0; index < numStudents; index++)
{
[...]
studentsPtr[index]->setID(tempID); // BOOM!
Here you are trying to use studentsPtr as if it was if it was the base-address for an array of pointers-to-Student, i.e. by offsetting its location by index pointers and dereferencing that location. But it's not really pointing to an array-of-pointers, it is pointing to a single pointer (i.e. it is pointing to the variable students), so whenever index is non-zero, you are invoking undefined behavior and therefore (in your case) you get a crash.
Let's debug it:
Since you didn't provide a complete test case, I changed the number of students to 3 and the number of tests to 0:
student_records.dat
1
Foo
Bar
2
Foo2
Bar2
3
Foo3
Bar3
My crash occurs in setID, but that's okay. this is 0xCCCCCCCC, which is the value given to uninitialized data by MSVC in debug mode. Great, the object pointer is garbage. Where does it come from? We'll go up the call stack to see:
This brings us to the following line in the loop of main that reads the input:
studentsPtr[index]->setID(tempID);
First, let's look at the variables:
We know the object is garbage. We can verify that here. Our object is studentsPtr[index], which is shown with the same uninitialized value. We also see that studentsPtr itself points to the proper first student. Finally, the index variable has the value 1, so we're on the second student.
studentsPtr[1] has a value that MSVC provides for uninitialized memory. Why is it uninitialized? Let's go back to the declaration:
Student *students = new Student[numStudents];
Student **studentsPtr = &students;
studentsPtr is set to be a pointer to a pointer to students. The inner pointer is actually an array of students. The outer pointer, however, is one solitary Student*. When indexing it like studentsPtr[1], we go beyond the single pointer within and trample onward to a nonexistent Student*. Then we try to write to that and the program thankfully blows up early.
The solution is to get rid of the double pointer. All that's needed is a bunch of Students. One pointer is one (unrecommended way to represent an) array:
Student *students = new Student[numStudents];
...
students[index].setID(tempID);
Now since the number of elements is known at compile-time, the recommended type would be std::array (std::array<Student, numStudents> students;), which can be used with the same syntax as the above after its declaration. If the size were not known at compile-time, the recommended type would be std::vector, which also shares the same syntax to access elements.
Technically, you can fulfill the -> requirement using a std::array as well. Simply obtain a pointer to the element and then use the arrow:
(&students[index])->setID(tempID);
More likely, the requirement is still looking for the manual free store memory management that you're doing. It's also easy to fit the arrow into that:
(students + index)->setID(tempID);
If you really, really need the double pointer even though it serves no purpose, remember that your array is the inner pointer, not the outer one:
((*students) + index)->setID(tempID);
If you're thinking the arrow hinders readability in all of these scenarios, you're correct. Perhaps the instructor has something specific in mind where it does not.
What happens when the double pointer is removed?
=========================================================
Student ID: 1
Student Name: Foo Bar
Average: -nan(ind)
Test Scores:
=========================================================
=========================================================
Student ID: 2
Student Name: Foo2 Bar2
Average: -nan(ind)
Test Scores:
=========================================================
=========================================================
Student ID: 3
Student Name: Foo3 Bar3
Average: -nan(ind)
Test Scores:
=========================================================
Success. The average is meaningless because I simplified the input file by changing the number of tests to 0. Long story short, the debugger provides the tools that can get debugging jobs done. Just from the debugger, we reduced the problem to the double pointer pointing to only one thing instead of multiple things. That's a much smaller scope for a problem than the original one.

My bool function keeps returning true and im not sure why

Im doing an excercise sheet to get an understanding of functions and I am currently working on the following question.
Write function prototypes for each of the following:
A function HasValue that may be passed a reference to an array, the size of the array and a
search value. The function should return true if the search value exists in the array
In my code I have sent the contents of the array, the array size and the value to be searched in the array to the bool function.
In the function I compared the value to each element of the array using a for loop.
I then created a variable count in the function that will be incremented if the value matches any element in the array.
I then used an if else statment to return true if count is greater than 0 and false if count is equal to 0. The problem is however that the function is only returning true thus the output will always be "this number appears in the array"
Logically these steps seem correct to me but obviously there is a flaw somewhere that I cant see. I presume its just I do not have a decent understanding of Bool functions yet but if someone could explain where and why I'm going wrong it would be greatly appreciated in my learning process to understanding functions and c++.
#include <iostream>
#include <iomanip>
#include "stdafx.h"
using namespace std;
bool HasValue(int Array[], int size, int Value);
int main()
{
int value;
int Array[10]{ 3,5,6,8,9,1,2,14,12,43 };
cout << "enter value you wish to search for in array " << endl;
cin >> value;
HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;
return 0;
}
bool HasValue(int Array[], int size, int Value)
{
int count = 0;
for (int i = 0; i < size; i++)
{
if (Value == Array[i])
{
count++;
}
}
if (count > 0)
{
return true;
}
else
return false;
}
You test code is the problem
HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;
This ignores the return value of HasValue and always prints "This number appears in the array".
HasValue(Array, 10 , value);
This line of code executes the function but ignores the returned value. When a function returns a value, you need to assign it to a variable:
bool result = HasValue(Array, 10 , value);
Then if (true) does not have any reference to the returned value. The true inside the if will cause the first cout to always print. You will never see the output from the else. But once you have the return value in a variable, you can use it in the if:
if(result)
You can reduce this all to one line of code, if you want:
if(HasValue(Array, 10 , value))
Now the if statement will directly test the return value from HasValue(). In this particular case, combining the code into a single line seems reasonable. You must be careful doing this, though. When you combine too much into a single line, the code becomes more difficult to debug. You will need to find a balance between readability and convenience as you continue learning how to program.

passing a returned pointer of a dynamical two-dimensional array to a sub-function and addressing the array

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:
int** productionTable=new int*[num1];
...
return* productionTable;
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 Production and productionTable (at all places) as int**, return productionTable in Production and use productionTable[i][j] for element retrieval.
I haven't been able to wade through the creation of your table fully, so there may well be problems there. Just looking at the end bit though, it seems that you're trying to print a one-dimensional array in two dimensions, which is straightforward, you just need to keep track of how far into the array you are on each row.
For each row, you need to offset your column index by (number of columns * number of rows already printed).
It looks like num1 is the total number of rows and num2 is the total number of columns. i is the number of rows completed already. So i*num2 is the offset required to read the row you are trying to print.
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*num2+j];
}
cout<<endl;
}