2016-10-01 66 views
0

我剛剛開始編寫代碼,並且正在學習有關數組的知識。我正在編寫一個程序,它接受一個數組列表,並告訴我第一個還是最後一個數字是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 
+0

什麼是錯誤? – Ryan

+0

我只是將它添加到問題 –

+0

聲明應該是'bool firstlast(int array [size]);' - 它需要與函數定義一致並提供數組的類型。 –

回答

0

此代碼

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

試圖通過陣列的size個元素不是數組本身。在C++中,數組是通過指針傳遞的,即使你使用數組語法編寫函數參數。

爲了避免混淆自己,改變firstlast

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

bool check = firstlast(array, size); 
+0

謝謝!但爲什麼我需要在參數中包含「int size」? –

+0

@JoshSimani因爲這個信息會失去,否則。請參閱[這裏](http://stackoverflow.com/questions/1461432/what-is-array-decaying)。 –

1

編譯器識別您的功能精細調用它。

的問題是在代碼中調用函數

bool check = firstlast(array[size]); 

它試圖array[size](一個不存在的array元件)傳遞給期待一個指針的函數的方式。

呼叫,據推測,應該是

bool check = firstlast(array); 

由於傳遞給函數當陣列被隱式轉換爲指針。