从'int'到'int(*)[3]'的无效转换c ++ [英] Invalid Conversion from 'int' to 'int(*)[3]' c++
问题描述
在代码的一些地方,我得到了 [Error]从'int'到'int(*)[3]'[-fpermissive]
的无效转换.该代码段尤其存在该错误
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
void getSquare(int square[3][3]){
int column;
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 >> column;
cout << endl;
square[i][j] = square[i][column];
}
}
}
此代码旨在接收9个数字并将它们存储在[3] [3]数组中,我可能完全错了,但请告诉我!
This code is designed to take in 9 numbers and store them in a [3][3] array, I might have this completely wrong but let me know!
这是为那些问过的人调用代码的方式
Here is how the code is being called for those of you who asked
int main(){
int magicSquare[3][3];
getSquare(magicSquare[3][3]);
checkSquare(magicSquare[3][3]);
if (checkSquare(magicSquare[3][3]) == true)
{
cout << "Yes!"
}
if (checkSquare(magicSquare[3][3]) != true)
{
cout << "No!"
return 0;
}
推荐答案
int main(){ int magicSquare[3][3]; getSquare(magicSquare[3][3]); return 0; }
不将数组传递给函数,而是将第4列和第4行中的(不存在的)元素传递给数组(在c和c ++中,数组的索引为0).这就是错误消息的原因,因为您正试图将一个整数(矩阵元素)分配给一个指向三元素数组的指针(这就是 getSquare(int square [3] [3])实际上期望-在这种情况下,
int square [3] [3]
等效于 int square(*)[3]
).
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);}
但是,您的 getSquare
可能不会达到您的期望(它将正方形的一个条目分配给另一个).您可能想写
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;
}
}
}
相反.
这篇关于从'int'到'int(*)[3]'的无效转换c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!