【问题标题】:invalid conversion from 'int' to 'int*' [-fpermissive] on passing array传递数组时从 'int' 到 'int*' [-fpermissive] 的无效转换
【发布时间】:2017-09-15 05:46:28
【问题描述】:

我是 C++ 语言的新手,我不知道指针及其用法。在线编译时遇到错误"[Error] invalid conversion from 'int' to 'int*' [-fpermissive]"

cout << midd (ax [10], asize) << endl;

这是代码:

#include <iostream>

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

int main() {
    int ax[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int asize = 10;
    cout << midd(ax[10], asize) << endl;
}

double midd(int arr[10], int size) {
    int acount = 0;
    int mid1;
    int mid2;
    int amid = size / 2;

    double mid = 0.0;

    while (acount < 10) {
        if (acount == amid) {
            mid1 = arr[acount];
        }
        else if (acount == (mid + 1)) {
            mid2 = arr[acount];
        }
        ++acount;
    }    
    mid = (mid1 + mid2) / 2.0;
    return mid;
}

【问题讨论】:

  • 请不要发送垃圾语言标签。您的代码不是 C,而是 C++,它是一种不同的语言。

标签: c++ arrays function


【解决方案1】:

这里 midd(int arr[10],int size); 期待 int* 并且您正在尝试传递 int 值( ax[10] 这也是错误:ax 只有 10 个元素,您尝试使用第 11 个),编译器无法转换 intint*,所以它显示“[错误]从'int'到'int*'的无效转换[-fpermissive]”。

要使该程序正确,您必须进行此更改。

  • cout&lt;&lt; midd (ax[10], asize ); 替换为cout&lt;&lt; midd (ax, asize );

    -现在 ax (int*) 的指针已传递,因此 midd() 将接受它。

【讨论】:

    【解决方案2】:

    更改函数调用

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

    和声明

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

    或采用 C++ 方式:std::vectorstd::array。例如

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

    【讨论】:

    • @Bob__ 最新编辑未反映在答案中。感谢您指出。
    【解决方案3】:

    你需要传递一个指向数组第一个元素的指针。将midd (ax [10], asize ) 更改为midd (ax, asize )

    在函数签名中

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

    参数int arr[10]等价于int *arr

    double midd(int *arr,int size);
    

    因此,midd 期望它的第一个参数为 int * 类型。在函数调用midd (ax, asize )中,ax会衰减为int *

    【讨论】:

    • 我写了另一个几乎相同的数组传递,不需要指针传递那么为什么要这样做呢??
    • @drainzerrr;没找到你?
    猜你喜欢
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2019-11-19
    • 1970-01-01
    • 2016-06-06
    相关资源
    最近更新 更多