Invalid Conversion from 'int' to 'int(*)[3]' c++

前端 未结 1 457
无人及你
无人及你 2021-01-15 19:25

I\'m getting [Error] invalid conversion from \'int\' to \'int(*)[3]\' [-fpermissive] in a few spots of my code. This snippet in particular has that error

<
相关标签:
1条回答
  • 2021-01-15 19:55
    int main(){ int magicSquare[3][3]; getSquare(magicSquare[3][3]); return 0; } 
    

    Doesn't pass an array to the function, but the (non-exising) element in the 4th colum and 4th row (arrays are 0-indexed in c and c++). That is the reason for the error message, as you are trying to assign an integer (the matrix element) to a pointer to a three element array (that is what getSquare(int square[3][3]) actually expects - int square[3][3] is equivalent to int square(*)[3] in this context).

    To pass the matrix you can write

    int main(){ int magicSquare[3][3]; getSquare(magicSquare);} 
    

    However, your getSquare will probably not do what you expect (it assigns one entry of the square to another one). You probably wanted to write

    void getSquare(int square[3][3]) {
    
        int number;
    
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                cout << "Please enter a number between 1 and 9" << endl;
                cin >> number;
                cout << endl;
                square[i][j] = number;
            }
        }
    }
    

    instead.

    0 讨论(0)
提交回复
热议问题