0

I'm just starting to code, and am learning about arrays right now. I am trying to write a program that takes in a list of arrays, and tells me if the first or last number is a 2. To do this, I'm using a function.

My code looks like:

    #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;
    }

What am I doing wrong? The compiler gives me the error:

candidate function not viable: no known conversion from 'int' to 'int *' for 1st argument; take the address of the argument with and
Josh Simani
  • 107
  • 10

2 Answers2

1

The compiler is recognising your function fine.

The problem is in the manner your code calls the function

bool check = firstlast(array[size]);

which attempts to pass array[size] (a non-existent element of array) to a function expecting a pointer.

The call, presumably, should be

bool check = firstlast(array);

since arrays are implicitly converted to pointers when passed to functions.

Peter
  • 35,646
  • 4
  • 32
  • 74
0

This code

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

tries to pass the sizeth element of array not the array itself. In C++ arrays are passed by pointer, even if you write the function parameter with array syntax.

To avoid confusing yourself, change firstlast to

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

and call it with

bool check = firstlast(array, size);
kfsone
  • 23,617
  • 2
  • 42
  • 74