C++,从`int*' 到`int' 的无效转换错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13706095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:39:54  来源:igfitidea点击:

C++, error invalid conversion from `int*' to `int'

c++

提问by user1876088

I have the following C++ code:

我有以下 C++ 代码:

#include <iostream>
using namespace std;
int main(){
}
int findH(int positionH[]){
    return positionH;         //error happens here.
}

The compiler throws an error:

编译器抛出一个错误:

invalid conversion from `int*' to `int'

What does this error mean?

这个错误是什么意思?

回答by Pavenhimself

positionH[]is an array, and its return type is int.

positionH[]是一个数组,它的返回类型是int

The compiler will not let you do that. Either make the parameter an int:

编译器不会让你这样做。要么将参数设为 int:

int findH(int positionH){
    return positionH;        
}

Or make the return type a pointer to an int:

或者使返回类型成为指向 int 的指针:

int* findH(int positionH[]){
    return positionH;        
}

Or convert the array to an integer before return:

或者在返回之前将数组转换为整数:

int findH(int positionH[]){
    return positionH[0];
}

回答by CashCow

This line is invalid C++ (and invalid C too, which your code appears to be written in):

这一行是无效的 C++(也是无效的 C,你的代码似乎是用它编写的):

int bla[2] = findH(field, positionH);

bla is an array of 2 elements and cannot be initialised that way. findH returns int.

bla 是一个包含 2 个元素的数组,不能以这种方式初始化。findH 返回整数。

回答by Ramanand Yadav

This error is coming while you are trying to do:

当您尝试执行以下操作时会出现此错误:

int *p =10;

that means you are assigning intvalue to pointertoint *p.

这意味着您正在int为 pointertoint 赋值*p

But pointer is storing address that means *pis taking 10as address.

但是指针正在存储地址,这意味着*p将其10作为地址。

So just do:

所以只需这样做:

int i=10;
int *p=&i;

or

或者

p=&i;

it will not give any error.

它不会给出任何错误。

回答by Desert Ice

The error was caused because you returned a pointer and the compiler is expecting a int.

错误是因为您返回了一个指针,而编译器需要一个 int。

There is a very BIG difference between int * and int.

int * 和 int 之间有很大的区别。

Also why are you returning positionH, arrays are passed by reference, there is no need to return it.

另外你为什么要返回positionH,数组是通过引用传递的,没有必要返回它。

Better code would be

更好的代码是

void option1(char** field, int[])   
   {
     int  findH(char **, int[]); 
     int positionH[2];
    findH(field, positionH);
      //positionH passed by reference, no need to return it
    }

void  findH(char **field, int positionH[])
{
    for(int n = 0;n < 14 ; n++)
    {
        for(int m = 0; m < 14; m++)
        {
                   if(field[m][n] == 'H')
                   {

                   positionH[0] = n;
                   positionH[1] = m;

        }
         }
    }

}