I need a dynamic 2D array of ints, it will represent a standard matrix. The size and elements are read in from a file at runtime.
Taking direction from other stack posts I've setup my array as follows;
void buildArray(ifstream &file, int** 2dArray);
void buildQueue(Queue<int> &Q, int** 2dArray);
int main()
{
int** 2dArray;
Queue<int> Q;
//...
// open file
//...
buildMatrix(file, 2dArray)
buildQueue(Q, 2dArray)
}
void buildArray(ifstream &file, int** 2dArray)
{
int size, element;
while (file.good()) {
file >> size;
2dArray = new int*[size];
for (int i = 0; i < size; i++)
2dArray[i] = new int[size];
// now I should be able to use 2dArray[r][c]
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
file >> element;
2dArray[i][j] = element;
}
}
}
Then I need to read the ints stored at each position [r][c] and build a queue. I think my problem is dereferencing the pointers... but I'm not sure.
void buildQueue(Queue<int> &Q, int** 2dArray)
{
int row, column, element;
// size is passed in as well, size is our rows or columns size here
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
row = i;
column = j;
element = 2dArray[i][j]; // getting seg fault here!
Q.push_back(row, column, element);
}
}
}
I should add that I know I could use vectors. I'm challenging myself here to responsibly build, use and deallocate a 2D array using pointers.
int *table = new int [size*size];and accessed withtable[column+size*row](or make simple wrapper class around this)?int *rows[]and avoid overhead of having heap block for every row. Or justint *rowarray = table + row * size.