invalid conversion from 'int' to 'int*' [-fpermissive] on passing array

前端 未结 3 403
野趣味
野趣味 2021-01-25 03:26

I am new to C++ language and I have no idea of pointers and their usage. I\'m facing the error \"[Error] invalid conversion from \'int\' to \'int*\' [-fpermissive]\"

相关标签:
3条回答
  • 2021-01-25 03:48

    You need to pass a pointer to the first element of array. Change midd (ax [10], asize ) to midd (ax, asize ).

    In function signature

    double midd(int arr[10],int size);
    

    parameter int arr[10] is equivalent to int *arr

    double midd(int *arr,int size);
    

    Therefore, midd expects its first argument of the type int *. In function call midd (ax, asize ), ax will decay to int *.

    0 讨论(0)
  • 2021-01-25 03:58

    Here midd(int arr[10],int size); is expecting int* and you are trying to pass int value ( ax[10] which is also ERROR : ax has only 10 elements and you try to use 11th ), and compiler can not convert int to int* so it shows "[Error] invalid conversion from 'int' to 'int*' [-fpermissive]".

    To make this program correct you have to make this change.

    • Replace cout<< midd (ax[10], asize ); with cout<< midd (ax, asize );

      -now pointer of ax (int*) is passed so midd() will accept it.

    0 讨论(0)
  • 2021-01-25 04:02

    Change the function call

    cout << midd(ax, asize) << endl;
    

    and declaration

    double midd(int arr[], int size) { ... }
    

    or go the C++ way: std::vector or std::array. For example

    #include <iostream>
    #include <array>
    using namespace std;
    
    double midd(array<int, 10> a) {
        int mid = a.size() / 2;
        return (a[mid] + a[mid + 1]) / 2.0;
    }
    
    int main() {
        array<int, 10> ax = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        cout << midd(ax) << endl;
    }
    
    0 讨论(0)
提交回复
热议问题