c++arraysfunctionnamespacesvariable-length-array

C++ - Candidate function not viable: no known conversion from 'double[10][Globals::MAX_COL]' to 'double (*)[Globals::MAX_COL]'


When compiling my program, I get the following error:

No matching function for call to 'fillWithRandomNum' Candidate function not viable: no known conversion from 'double[10][Globals::MAX_COL]' to 'double (*)[Globals::MAX_COL]'

Whenever I change Globals::MAX_COL to a number (i.e. 10), it works properly. How would I move forward with using the namespace variable Globals::MAX_COL?

Matrix.h:

#include "namespaces.h"

#ifndef MATRIX_H
#define MATRIX_H

void fillWithRandomNum(double[][Globals::MAX_COL], const int);

#endif

namespaces.h:

#ifndef namespaces_h
#define namespaces_h

namespace Globals {
    int MAX_COL = 10;
};

#endif

main.cpp:

#include <iostream>
#include "Matrix.h"
#include "namespaces.h"

int main() {
    double matrix[10][Globals::MAX_COL];
    
    fillWithRandomNum(matrix, 10);
    
    return 0;
}

I tried using pointers by changing the function declaration and the code to the following, but I get the same error:

void fillWithRandomNum(double (*matrix)[Globals::MAX_COL], const int);

Solution

  • In

    namespace Globals {
        int MAX_COL = 10;
    };
    double matrix[10][Globals::MAX_COL];
    

    as MAX_COL is not a constant expression, matrix is VLA (Variable length array).

    It is not standard C++, but compiler might provide it as extension.

    If value is really intended as non-constant, use resizable container as std::vector.
    If value should be const, add missing const, and potentially use std::array.