我从g++编译器得到这个错误-从“int*”到“int”的转换无效[-fpermission]

i am getting this error from g++ compiler - invalid conversion from ‘int*’ to ‘int’ [-fpermissive]

本文关键字:int 无效 -fpermission 转换 编译器 g++ 错误 我从      更新时间:2023-10-16

我的完整程序如下:

#include<iostream>
using namespace std;
int max(int *,int); 
int main()
{
    int n, a[10], b;
    cout << "Please enter the no. of integers you wish to enter ";
    cin >> n;
    for(int i = 0; i < n; i++)
    {
        cout << endl << "please enter the " << i+1 << " no. ";
        cin>>a[i];
    }
    b = max(&a[0], n);
    cout << endl << "The greates no. is " << a[b] << " and its index position is " << b;
    return 0;
}
int max(int * ptr,int n)
{
    int b[10], i, max, k;
    &b[0] = ptr;
    max = b[0];
    for(i = 0; i < n; i++)
    {
        if (max < b[i]);
        max = b[i];
        k = i;
    }
    return k;
}

我想把指针传给函数,然后找到最大的数字。我不确定传递数组是否算作传递指针。

您不需要为b[10]分配内存,只需要在这里有一个指针,而不是

int b[10];

只需声明一个指针,并将其地址设置为函数传递的数组的起始元素。

int* b= ptr; 
#include<iostream>
using namespace std;
int  max(int *,int);
int main()
{
    int n,a[10],b;
    cout<<"Please enter the no. of integers you wish to enter ";
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cout<<endl<<"please enter the "<<i+1<<" no. ";
        cin>>a[i];
    }
    b=max(a,n);
    cout<<endl<<"The greates no. is "<<a[b]<<" and its index position is "<<b;
    return 0;
}
int max(int *a,int n)
{
    int i,max,k=0;
    //&b[0]=ptr;
    max=a[0];
    for(i=1;i<n;i++)
    {
        if(max<a[i])
            max=a[i];
        k=i;
    }
    return k;
}

试试这个程序
它不使用b[],这实际上是不必要的,只传递数组a作为参数。

更改

b=最大值(a,n(;

int max(int *a,int n)
{
    int i,max,k=0; // INITIALIZE k !
    //&b[0]=ptr;
    max=a[0];
    for(i=1;i<n;i++)
    {
        if(max<a[i])
            max=a[i];
        k=i;
    }
    return k;
}

您应该将K初始化为0

您的函数无效您不能进行赋值

&b[0] = ptr;

这样的赋值没有意义,因为它试图更改数组元素b[0]的地址。

您不需要在函数中声明任何额外的数组。

此外,您的函数有未定义的beahviour,以防第一个元素是数组的最大元素。在这种情况下,函数返回未初始化的变量k。在if语句之后还有一个分号

if (max < b[i]);

因此,这种说法也毫无意义。

功能可以写得更简单

int max( const int * ptr, int n )
{
    int max_i = 0;
    for ( int i = 1; i < n; i++ )
    {
        if ( ptr[max_i] < ptr[i] ) max_i = i; 
    }
    return max_i;
}

将表达式更改为:

b=max(a,n);

您不需要通过引用传递数组,它们是通过引用自动传递的。

也发生了变化:&b[0]=ptr;b=ptr;
但为此将b初始化为int * b;

或者简单地说,
不要将ptr的值分配给b,只需直接处理ptr即可。