0

Hey so I want to declare an 2d array in one of my classes - it is first declared outside of any methods, and then set size by constructor

class xxx
int **triangle;


constructor(int n){
    triangle = new int *[n+1];
    for(int i=0;i<=n; i++) triangle[i]=new int[i+1];
}

but the first line of constructor does not work:

 error: incompatible types in assignment of ‘int**’ to ‘int* [0]’

NVM it's fixed - I put int *triangle[]; in my header file.. 40 minutes wasted :D

user3369008
  • 105
  • 11

2 Answers2

3
int constructor(int n)
{
    int** triangle = new int*[n + 1];
    for(int i = 0; i <= n; ++i)
        triangle[i] = new int[i + 1];
}
jacekmigacz
  • 789
  • 12
  • 22
0

Alternate Solution

Declaring 2D array using std::vector instead of raw pointer

n x n matrix:

 std::vector<std::vector<int> >  triangle( n, std::vector<int>(n, 0) );

row x col matrix

 std::vector<std::vector<int> >  triangle( row, std::vector<int>(col, 0) );

Note: Both the 2d arrays using std::vector are initialized by 0.

SridharKritha
  • 8,481
  • 2
  • 52
  • 43