/*Edit: I'm not sure if I did something wrong, but some of the comments and the downvotes are making me feel really dumb for asking a simple question.
I appreciate the constructive criticism as I am a complete coding noobie. For those of you who did help I really appreciate it and I did learn quite a bit.
I just wish some of you were less rude when it came to answering my question. Oh well, bring on the downvotes. */
Hi guys this is my first question here! I created a simple Array class that allows the user to create a dynamic 2D array with specified rows and cols. Everything works fine until the destructor is called and I try to delete the dynamically created data array.
I will supply my header and implementation file:
/* Array.h
* Array Class Header File
*/
#ifndef ARRAY_H
#define ARRAY_H
class Array{
private:
int row;
int col;
int **data;
public:
Array(int,int);
~Array();
int getRow() { return row;}
int getCol() {return col;}
int getData(int,int);
};
#endif
/* Array.cpp
* Array implementation file
*/
#include <iostream>
#include <cstdlib>
#include "Array.h"
using namespace std;
//Constructor
Array::Array(int rowIn,int colIn){
// RowIn and ColIn must be greater than 1 to create matrix
if(rowIn <= 1 || colIn <= 1){
cout << "Row and column must be greater than 1" << endl;
return;
}
// If they are greater than 1 then set member variables
row = rowIn;
col = colIn;
// Allocate memory for 2D Array
data = new int*[row];
for(int i = 0; i < row; i++){
data[i] = new int[col];
}
// Fill 2D array with random numbers
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
data[i][j] = rand()%90 + 10;
}
}
}
// Getter function that returns data at row and col
int Array::getData(int row,int col){
return data[row][col];
}
//Destructor
Array::~Array(){
for(int i = 0; i < row; i++){
delete[] data[i];
}
delete []data;
}
/* Main.cpp
* File to test array class
*
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Array.h"
using namespace std;
void printArray(Array);
int main(){
int t = time(0);
srand(t);
Array test(10,10);
printArray(test);
return 0;
}
void printArray(Array a){
for(int i = 0; i < a.getRow(); i++){
for(int j =0 ; j < a.getCol(); j++){
cout << a.getData(i,j) << " ";
}
cout << endl;
}