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

时间:2014-03-16 17:37:28

标签: c++ pointers casting

我的完整程序如下:

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

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

4 个答案:

答案 0 :(得分:3)

你不需要为b [10]分配内存,你只需要一个指针,而不是

int b[10];

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

int* b= ptr; 

答案 1 :(得分:2)

#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 = MAX(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

答案 2 :(得分:2)

您的功能无效您可能无法进行作业

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

答案 3 :(得分:0)

将表达式更改为:

b=max(a,n);

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

也改变了: &b[0]=ptr;b=ptr;
但是为了初始化b为int * b;

或简单地说,
不要将ptr的值赋给b,只需直接在ptr上工作。

相关问题