g++编译器无法识别我的函数

g++ compiler is not recognizing my function

本文关键字:我的 函数 识别 编译器 g++      更新时间:2023-10-16

我刚刚开始编写代码,现在正在学习数组。我正在尝试编写一个程序,该程序接收数组列表,并告诉第一个或最后一个数字是2。为此,我使用了一个函数。

我的代码看起来像:

    #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]);

其试图将CCD_ 1(array的不存在的元素(传递给期望指针的函数。

电话,大概应该是

bool check = firstlast(array);

因为数组在传递给函数时被隐式地转换为指针。

此代码为

bool check = firstlast(array[size], size);

尝试传递数组的第CCD_ 3个元素,而不是数组本身。在C++中,数组是通过指针传递的,即使使用数组语法编写函数参数也是如此。

为了避免混淆自己,请将firstlast更改为

bool firstlast`(int* array, int size)`

并用称之为

bool check = firstlast(array, size);