1

I have a struct type

typedef struct {

Point CellLocation;
enumCell isOccupied;
Node* coveringStation;
vector< pair<float,Node*> > coveredBy;
} Cell;

Then trying to declare 2D array of cells, using dynamic input such as:

this->Height = par("Height");
this->Width =  par("Width");

Cell **c;

c = new Cell*[Width];
for (int i = 0; i < Width; i++)
    Cell[i]= new Cell[Height];

I get this output:

 error: expected unqualified-id before ‘[’ token

on Cell[i]= new Cell[Width];

what am I doing wrong?

CosminO
  • 5,018
  • 6
  • 28
  • 50
e.semyono
  • 63
  • 1
  • 7

2 Answers2

4

Cell is your typename

you want to do c[i] = new ...

benjymous
  • 2,102
  • 1
  • 14
  • 21
1

In C++, you don't need C-style typedef struct {...} ...: you can just define a struct without typedef, like this:

struct Cell {
   Point CellLocation;
   enumCell isOccupied;
   ....       
};

Moreover, instead of using raw C-style arrays allocated with new[] (and manually freed with delete[], and exception-unsafe), you can use C++ convenient container classes, like a std::vector containing another std::vector, e.g.:

// 2D matrix of cells (as vector of vector)
vector<vector<Cell>> cells;

// Create the rows
for (size_t i = 0; i < Height; i++) {
    // Add an empty row
    cells.push_back(vector<Cell>());
}

// Add columns to each row
for (size_t j = 0; j < Width; j++) {
    for (size_t i = 0; i < cells.size(); i++) {
        cells[i].push_back(Cell());
    }
} 

And you can use the cells[i][j] syntax to access single elements in the matrix.

An alternative would be to use a single vector, simulating a 2D matrix:

// 2D matrix, simulated using a 1D vector
vector<Cell> cells(Height * Width);

// Access element at index (row, column), using:
cells[row * Width + column] = ... ;
Mr.C64
  • 41,637
  • 14
  • 86
  • 162
  • Is the processing of vectors is slower than good old double pointers? timewise... assuming i can have tens of thousands of cells in that array. – e.semyono Nov 04 '13 at 12:34
  • 1
    A `std::vector` has some space-overhead over a single raw pointer (a `std::vector` in some implementations may contain three pointers, because it manages dynamically growths, etc.). But element access is just _O(1)_, just like for raw arrays (if you use `std::vector::operator[]` overload). If you use the technique of a single `std::vector` that simulates 2D matrix, this is very efficient for element access (also becaue of good locality, which is not achieved in the `vector>` case), just as with raw pointers. – Mr.C64 Nov 04 '13 at 13:56