2D array of object pointers in C ++

How do you allocate a 2D array of pointers to objects?

I currently have:

file.h

extern ClassName **c;

file.cpp

ClassName **c;
int main(){
    // some stuff
    c = new ClassName*[sizex];
    for(int i = 0; i < sizex; ++i){
        c[i] = new ClassName[sizey];
    }

    for(int i = 0; i < sizex; ++i){
        for(int j = 0; j < sizey; ++j){
            c[i][j] = new ClassName();
        }
    }

That fails to compile with an error, indicating that there is no match for the = operator using ClassName and ClassName * that look at the error. But if I were to change the assignment c [i] [j] to

ClassName cn();
c[i][j] = cn;

This gives many other errors. The size of the array cannot be known before execution (reading from stdin), and it must also be external. What is the correct way to declare an array in this case?

+4
source share
5 answers

You must declare a pointer as

extern ClassName ***c;

The distribution will look like

c = new ClassName**[sizex];
for(int i = 0; i < sizex; ++i){
    c[i] = new ClassName*[sizey];

    for(int j = 0; j < sizey; ++j){
        c[i][j] = new ClassName();
    }
}

2D-, T. T ClassName *

ClassName cn();

, ClassName .

+4
ClassName *p1;

p1 ClassName ClassName s.

ClassName **p2;

p2 ClassName* ClassName* s.

*p2 ClassName ClassName s.

:

   c[i] = new ClassName[sizey];

, c[i][j] ClassName, ClassName*.

c[i][j] = ClassName(); , c[i][j] = new ClassName();, c :

 ClassName*** c;

std::vector .

 std::vector<std::vector<std::unique_ptr<ClassName>>> c;
+2

, typedefs:

typedef ClassName* Row;
typedef Row* Matrix;

Matrix *M;  //equivalent to : ClassName ***M, 
            //check by substiting Matrix with Row* and Row with ClassName*
int main()
{
   M = new Matrix[numRows];

   for(int row = 0; row < numRows; ++row)
   {
        M[row] = new Row[numCols];

        for(int col = 0; col < numCols; ++j)
        {
            M[row][col] = new ClassName();
        }
    }
}

.

+1
source

You need to change your type to: ClassName *** c; as Vlad from Moscow noted.

ClassName **c;
int main(){
    // some stuff
    c = new ClassName**[sizex];
    for(int i = 0; i < sizex; ++i){
        c[i] = new ClassName*[sizey]
    }

    for(int i = 0; i < sizex; ++i){
        for(int j = 0; j < sizey; ++j){
            c[i][j] = new ClassName();
        }
    }

Your usage should also change:

ClassName cn;
c[i][j] = new ClassName( cn );  // <-- this copy constructor would cause a memory leak (old pointer not deleted)
*(c[i][j]) = cn;                // <-- this would use the assignment operator.  May be weak performance.
ClassName & cn = *(c[i][]);     // <-- Allows you to work directly on the cell.
0
source

ClassName **cis a 2D array, i.e. c[n][m]objects ClassName.

You tried to assign c[n][m]type ClassNameas new ClassName()typeClassName*

for(int i = 0; i < sizex; ++i){
    for(int j = 0; j < sizey; ++j){
        c[i][j] = *(new ClassName);
    }
}
0
source

All Articles