mercredi 9 septembre 2020

Create a heap-based 2D array without using double pointer syntax?

I need to declare a 2D array as the member variable of a class. I can't use STL (so, no vector), and I've been asked to avoid double/triple pointers. I want to be able to reference elements in this 2D array using subscripting notation, e.g. arr[0][0]. The array also must be declared on the heap due to its size.

Due to the requirements I have, none of the existing answers on StackOverflow meet my needs.

What I've been trying to do is:

class MyClass {
 public:
  MyClass() : arr(new int[1000][2]) {}

  // other stuff here

 private:
  int arr[1000][2];
};

The error I get after compiling that class is "cannot initialize a parameter of type int * with an lvalue of type int[1000][2]". Clearly, I can solve this by using pointer syntax, but, as mentioned above, I've been asked to use "array syntax" for code clarity. I was hoping someone with a better understanding of C++ could explain how to use "array syntax".

Aucun commentaire:

Enregistrer un commentaire