S
Someonekicked
im trying to declare a two dimensional array using pointers. but it is not
working, any ideas?
working, any ideas?
im trying to declare a two dimensional array using pointers. but it is not
working, any ideas?
Someonekicked said:im trying to declare a two dimensional array using pointers. but it is not
working, any ideas?
Someonekicked said:im trying to declare a two dimensional array using pointers. but it is not
working, any ideas?
Angad said:I would say, the simplest way would be
int **p ;
p = new int *[ROWS] ;
for( int i = 0 ; i < ROWS ; i++ )
p = new int[COLUMNS];
But everyone seems to suggest vectors...
Someonekicked said:I'm trying to declare a two dimensional array using pointers.
Angad said:Yes, I agree that vectors simplify the matter a lot by reducing our
coding, but I must say that they add to a lot of unnecessary code to
the executable code. Compile time increases manyfold (I'm talking from
a personal experience). I'd say, use vectors only when basic data types
cannot be used....
As for the freeing of the memory, the code is:
for( int i = 0 ; i < ROWS ; i++ )
delete [] p ;
delete [] p ;
This code will definitely be faster than using vectors... (please
comment if I'm wrong)
Bushido said:It's not that I'm not allowed to use the vector class, I'm just not
interested in using vectors. I'm more comfortable with Arrays and
Pointers
I like Angad's method.
Here is what I'd really like to do with his codes:
class Matrix{
public:
Matrix(int rows = 4, int cols = 4){
setDims(rows,cols);
int **p ;
p = new int *[getRows()] ;
for( int i = 0 ; i < getRows() ; i++ ){
p = new int[getCols()];
};
};
Matrix &setDims(int rows,int cols){setRows(rows);setCols(cols);};
Matrix &setRows(int rows){this->rows = rows; return *this;};
Matrix &setCols(int cols){this->cols = cols; return *this;};
int getRows() const {return rows;};
int getCols() const {return cols;};
Matrix printMatrix() const {
for(int i = 0; i < getRows(); i++){
for(int j = 0; j < getCols(); j++){
cout << this[j] << " "; // I know this is incorrect, but I'm
just using it
// to illustrate the concept. Please correct if I am wrong.
};
cout << endl;
};
};
Matrix &setIdentity(){
for(int i = 0; i < getRows(); i++){
for(int j = 0; j < getCols(); j++){
this[j] = (i == j);
};
};
}; // Identity matrix
~Matrix(){
for( int i = 0 ; i < getRows() ; i++ ){
delete [] p ;
};
delete [] p ;
};
private:
int rows, cols;
};
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.