user1876088
user1876088

Reputation: 71

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

I have the following C++ code:

#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?

Upvotes: 6

Views: 68244

Answers (4)

Desert Ice
Desert Ice

Reputation: 4600

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

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

Also why are you returning "positionH", an array is passed by memory address, there is no need to return it.

Better code would be:

  Function

// "field" 4 by 3, and "postionH" will got the last H letter
void  findH(char** field, int positionH[]) {

  for (int n = 0; n < 4 ; n++) {
    for (int m = 0; m < 3; m++) {

      if (field[m][n] == 'H') {
        positionH[0] = n;
        positionH[1] = m;

      }
    }
  }

}

  "main" function

int positionH[2];

char** field;
field = new char* [ 4 * sizeof(char*)];
for (int row = 0; row < 4; row++) {
  field[row] = new char[3 * sizeof(char)];
}
field[0] = "SHH";
field[1] = "SSH";
field[2] = "HSH";
field[3] = "SHS";

// Call the above funtion
findH(field, positionH);

// Release memory
for (int n = 0; n < 4; n++) {
  delete field[n];
}
delete [] field;

Upvotes: 2

Ramanand Yadav
Ramanand Yadav

Reputation: 329

This error is coming while you are trying to do:

int *p =10;

that means you are assigning int value to pointertoint *p .

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

So just do:

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

or

p=&i;

it will not give any error.

Upvotes: 3

Pavenhimself
Pavenhimself

Reputation: 567

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

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

int findH(int positionH){
    return positionH;        
}

Or make the return type a pointer to an int:

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

Or convert the array to an integer before return:

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

Upvotes: 9

CashCow
CashCow

Reputation: 31425

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

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

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

Upvotes: 3

Related Questions