C ++ function calling 2d array

Hi guys, I have a constructor in the County.h class:

struct Country {
    Country(double**, int);
};

      

and basically I have graph[Size][Size]

, and I want to call the constructor for County

.

int main() {
    double graph[Size][Size];
    Country c(graph, 0);
}

      

But it gives me an error no matching function for call to ‘County::County(double [22][22], int)’

What can I do to fix this problem? Thanks you

+3


source to share


2 answers


double [Size][Size]

and double**

are not the same. Your compiler doesn't like this.

Change the constructor prototype or the way the array is declared. But you cannot directly pass an array of an array to a pointer to a pointer.

struct Country {
    Country(double[Size][Size], int);
};

      



OR

int main() {
    double** graph = new (double*)[Size];
    for (int i = 0; i < Size; ++i) {
        graph[i] = new double[Size];
    }
    Country c(graph, 0);

    // Don't forget to delete your graph then.
}

      

Note that the first one requires you to know the size before your code triggers its execution (for example, saving Size

in a macro), but the second code is longer than the code and you will have to manipulate a lot of RAM memory, which can lead to errors if you won't be careful.

+4


source


An alternative is to declare your constructor as a template and pass the array by reference ( const

),

struct Country {
    template<size_t N>
    Country(double /*const*/ (&arr)[N][N], int);
};

      



So the template will infer the size of the array directly. Of course the disadvantage is that the above won't work with double pointers. The upside is that the compiler will strictly check for type, and your program won't even compile unless an array is made from double

(no conversions are done on type inference) or if it's not a square.

+1


source







All Articles