Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a dynamic array without size in header, defining in .cpp

I'm writing a class which has dynamic two-dimensional array of integers as a field - most imporant part of it, short access time is preferable. I want to declare it in header file,

//Grid.h
class Grid{
  int ** array;
}

however the size and contents of it are yet to be defined in constructor implemented in cpp file (propably a read from ini file).

I'm not sure if declaring a int **array pointer in header and assigning later dynamically array to it with use of

array = new int*[x];  
 for(i=0;i<x;i++){    
array[i] = new int [y];    
}

will result in creating an array that will be accessible and cause no trouble in other functions calling directly to field of array[i][j] in their definitions (or other less obvious errors), however it's granted that before mentioned functions start calling in, it will and has to be defined already.

My question - it this the valid and efficient way to do it? I'll accept any other ideas.
Yes, I've heard of "vector" class but I'm not sure about it's efficiency or read-and-write vs integer array performance. Vectors are flexible in size, but I don't need it - my array once set, will have fixed size.

Propably I'm just too used to Java-style int[][] array code.

like image 343
Ponyman Avatar asked Nov 21 '25 04:11

Ponyman


1 Answers

Yes, your way is valid and efficient. Only problem you have (obviously) is to make sure that you don't exceed the limits (Java checks that for you, with C you will have to make sure you are between [0...x-1].

However, if you are speaking of high efficiency, the more efficient way would be to create a one-dimensional array and multiply your way into it. This would be more efficient in terms of memory usage (especially with small sizes) and access time. You could probably wrap the access functions in the grid class (Grid::Set(value, x,y), Grid::Get(x,y)) and check against size overruns yourself.

//Grid.h
class Grid{
    int maxx, maxy;
    int *array;

  public: 
     Grid(int x, int y);
     ~Grid();
     int Get(int x, int y);
}


// making the grid
Grid::Grid(int x, int y) 
{
    this->maxx= x; 
    this->maxy= y;
    this->array= new int[this->maxx*this->maxy];  
}

// destroying the grid
Grid::~Grid() 
{
    this->maxx= this->maxy= 0;
    delete []this->array;  
    this->array= NULL;
}

// accessing the grid
int Grid::Get(int x, int y)
{
#if DEBUG
    assert(x>=0 && x<this->maxx);
    assert(y>=0 && y<this->maxy);
#endif
    return this->array[ y*this->maxx + x];
}
....
like image 184
Nicholaz Avatar answered Nov 22 '25 18:11

Nicholaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!