我从g++编译器得到这个错误-从“int*”到“int”的转换无效[-fpermission]
i am getting this error from g++ compiler - invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
我的完整程序如下:
#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即可。
相关文章:
- 错误:从"int"到枚举c++的转换无效
- 多维数组 C++ 中数组下标的类型"int[int]"无效
- 从 'int' 到 'int*' CPP 的转换无效
- 无效 f(int) 的模板和 decltype
- 错误:从"int"到"int*"的转换无效[-允许].我在下面提供了我的代码,我
- 错误:数组下标的类型"int[int]"无效
- int* 和 int[] 类型对二进制运算符 + 的操作数无效
- 从类指针到 int 的转换无效
- C++ 错误:由于 swprintf 而从 'int' 到 'const wchar_t* 的转换无效
- 为什么 std::d eclval<int>() = std::d eclval<int>() 无效?
- 错误:数组下标的类型"const bool[int]"无效
- 2D数组中数组下标的类型"int[int]"无效
- 错误:数组下标的类型'int[int]'无效
- C++中的合并排序:无法在合并函数中传递数组 - 转换为'int*'无效
- 数组下标的类型"int[int]"无效
- 使用矢量的数组下标'int[int]'无效类型
- C++中的二进制补码 - 数组下标的类型"int[int]"无效
- 从“char*”到“char”[-fpermissive]的转换无效,数组下标的类型“char[int]”无效
- 无法解决错误:间接寻址需要指针操作数("int"无效)
- C++将数组相互分配;type int*=type int有效,但int=int*无效