g ++编译器无法识别我的功能
我刚刚开始编写代码,并且正在学习有关数组的知识。我正在编写一个程序,它接受一个数组列表,并告诉我第一个还是最后一个数字是2.为此,我使用了一个函数。g ++编译器无法识别我的功能
我的代码如下所示:
#include <iostream>
using namespace std;
const int size = 6;
bool firstlast(int array[size]);
int main()
{
int array[size];
for (int index = 0; index < size; index++)
{
cout << "Enter value for array[" << index << "]\n";
cin >> array[index];
}
bool check = firstlast(array[size]);
if (check)
cout << "The array either starts or ends in 2!\n";
else
cout << "The array does not start or end with 2.\n";
return 0;
}
bool firstlast(int array[size])
{
if (array[0] == 2)
return true;
if (array[size - 1] == 2)
return true;
return false;
}
我在做什么错? 编译器给我的错误:
candidate function not viable: no known conversion from 'int' to 'int *' for 1st argument; take the address of the argument with and
此代码
bool check = firstlast(array[size], size);
试图通过阵列的size
个元素不是数组本身。在C++中,数组是通过指针传递的,即使你使用数组语法编写函数参数。
为了避免混淆自己,改变firstlast
到
bool firstlast`(int* array, int size)`
与
bool check = firstlast(array, size);
谢谢!但为什么我需要在参数中包含“int size”? –
@JoshSimani因为这个信息会失去,否则。请参阅[这里](http://stackoverflow.com/questions/1461432/what-is-array-decaying)。 –
编译器识别您的功能精细调用它。
的问题是在代码中调用函数
bool check = firstlast(array[size]);
它试图array[size]
(一个不存在的array
元件)传递给期待一个指针的函数的方式。
呼叫,据推测,应该是
bool check = firstlast(array);
由于传递给函数当阵列被隐式转换为指针。
什么是错误? – Ryan
我只是将它添加到问题 –
声明应该是'bool firstlast(int array [size]);' - 它需要与函数定义一致并提供数组的类型。 –