1

So in my header file for a class Foo I declare a 2D array of ints like so:

int board[][];

I am intentionally leaving out a size because I want to set that in the constructor. board[][] will not change in size once initialized. One of my constructors looks like this:

Foo(int _board[][]);

In this I want to set board[][] to the same size as _board[][] and to also copy the contents. I have tried using this in the .cpp implementation of Foo:

Foo::Foo(int _board[][]){
board[][] = _board[][]; //Does not work as intended
}

However, this does not work as intended. How can I make board[][] be the same size and have the same contents as _board[][] in the constructor?

1
  • you cant do it using array without knowing the 2nd dimension size. Commented Oct 28, 2012 at 22:46

1 Answer 1

1

C++ is different than Java. int a[][]; is not allowed as variable type. Some misleading C++ feature is that first size is allowed to be left empty:

int foo(int a[]);
int foo(int a[][3]); 
int foo(int a[][3][4]); 

Another misleading C++ feature is that this is allowed in initialization of an array (compiler will count the size):

int a[][] = {{1,2}, {1,2,3,4}, {1}};

which is equivalent to:

int a[3][4] = {{1,2}, {1,2,3,4}, {1}};

For your very case - use std::vector:

std::vector<std::vector<int>> board;
Foo(std::vector<std::vector<int>> board) : board(board) {}

If you can't use std::vector for whatever reason - then only solution is to use int** with both sizes:

int** board;
size_t s1;
size_t s2;
Foo(int** board = NULL, size_t s1 = 0, size_t s2 = 0) : board(board), s1(s1), s2(s2) {}

But be aware that you cannot use this way:

int board[][] = {{1,1,2},{1,2,2}};
Foo foo((int**)board,2,3);

because you must provide a dynamic array:

int** board = new int*[2] { new int[3]{1,1,2}, new int[3]{1,2,2}};

And since that - you have to implement copy constructor, assignment operator and destructor:

Foo(const Foo& other) : TODO { TODO }  
~Foo() { TODO }  
Foo& operator = (Foo other) { TODO }

So, just use std::vector.

Sign up to request clarification or add additional context in comments.

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.