0

2D arrays such as:Cell **scoreTable.After allocating:

scoreTable = new Ceil*[10]; 
for(int i = 0 ;i<10;i++) 
scoreTable[i] = new Ceil[9]; 

And I want to save the value like this:scoreTable[i][j]= new Ceil(i,j) in heap,and this can not work in c++.Thanks for help.

2

3 Answers 3

1

scoreTable[i][j]= new Ceil(i,j). You are trying to put Cell* into Cell.

You have to create 2d array of pointers:

auto scoreTable = new Ceil**[10]; 
for(int i = 0 ;i<10;i++) 
    scoreTable[i] = new Ceil*[9]; 

But much better is to use vector:

std::vector< std::vector<Ceil*> > table;
table.resize(10);
for (int i = 0; i < 10; ++i)
{
    table[i].resize(9, NULL);
}
table[3][4] = new Ceil();
Sign up to request clarification or add additional context in comments.

2 Comments

I know this ,but it should make a lot of changes because this question appears when I convert java to C++,scoreTable is a Class Member.Thanks all the same.
It will cause not that many changes, as vector overloads operator[] and therefore acts like an array.
0

Once you've allocated your array like this, you'll already have a 2D array of Cell, so you don't need to use the new keyword to change the value.

If you give your Cell class a method like SetValue(i,j), then you can use it like this: scoreTable[i][j].SetValue(i,j);

1 Comment

I thought too much,thank you ,just add a new method ,it is good.
0

I want to suggest using std::vector instead. It is much easier to keep track of.

You can replace all of the code above with

std::vector< std::vector< Cell> > scoreTable(10, std::vector<Cell>(9));

This will create scoreTable, which is a vector containing 10 elements of vector<Cell>, each containing 9 cells. In other word, the desired 2D table.

You access the elements in the same way. scoreTable[i][j], where i goes fron 0 to 9, and j from 0 to 8.

If you want to expand with a new row, just say:

 scoreTable.push_bach(std::vector<Cell>(9));

For a new column:

for(size_t row = 0; row < scoreTable.size(); ++row) {
  scoreTable[row].push_back(Cell());
}

No need for new or delete.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.