1
struct Mystruct
{
  int x;
  int y;
  Mystruct(int x, int y);
}
------------------------
class Myclass
{
  Mystruct** p;
  Myclass(int n);
}
------------------------
Myclass::Myclass(int n)
{
  this->p = new Mystruct*[n];
  for ( int i = 0; i < n; i++ )
    this->p[i] = new Mystruct[n];
}

This will not work. I know the problem lies somewhere with default constructor not being available, but I do not know how to move forward from here.

7
  • this->p* why that '*' ? Commented Apr 23, 2020 at 10:48
  • this->p[i] is not an array pointer. try this->p[I] = new MyClass(); Commented Apr 23, 2020 at 10:48
  • 1
    First things first, i'll give the obligatory std::vector<std::vector<Mystruct>> p (n, std::vector<Mystruct>(n)); would be much safer and avoid manual memory management. Anyway, it's unclear to me what you want all the Mystruct to contain in terms of data. Commented Apr 23, 2020 at 10:49
  • I repaired it to this->p. @George It is a school project related where we are not allowed to use vectors. In Mystruct I want to have two integers x and y with information about a predescor on a chessboard. Commented Apr 23, 2020 at 10:52
  • 1
    Don't forget to write destructor: Commented Apr 23, 2020 at 10:52

1 Answer 1

2

you want

Myclass::Myclass(int n)
{
  this->p = new Mystruct*[n];
  for ( int i = 0; i < n; i++ )
    this->p[i] = new Mystruct[n];
}

because Mystruct** p;

You also need to save the dimension, and to add a destructor, very probably the constructor must be public.

As said in a remark to be able to allocate your array of Mystruct that one need a constructor without parameter

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

3 Comments

...and a default ctor to Mystruct, or that inner array-allocation is doomed.
Thank you guys, it seems that all the warnings evaporated as I wrote a default constructor. Is it ok to have an empty default constructor in this situation set as Mystruct::Mystruct(){} ?
@Milan yes else impossible to do new Mystruct[n];

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.