C++ Invalid Conversion of Int* to Int

  1. Pointer Preliminaries in C++
  2. the Conversion Error
  3. Resolve the Conversion Error
C++ Invalid Conversion of Int* to Int

This short tutorial will discuss the error message "Invalid conversation of int* to int". First, let’s have a recap of the pointers in C++.

Pointer Preliminaries in C++

Pointers are used to hold the address (a hexadecimal value) of a variable, and it is assigned to the pointer type variable using the ampersand sign(&), also known as the address operator preceded to the variable name.

Pointers are declared using the * symbol like this:

DataType *p;

We can assign the address of an integer variable to an integer pointer using the following statement:

int* p = &a;

The above line of code will assign the address of the integer variable a to the integer pointer p.

the Conversion Error

When an integer variable is assigned a hexadecimal address value of variable instead of an integer type value, the "invalid conversion from int* to int" error occurs.

Example Code:

#include <iostream>
using namespace std;

int main() {
  int a = 10;
  int p;
  p = &a;  // invalid conversion error
  cout << p;
}

The above code will generate a conversion error on line 07 as p is assigned an address of type int* that can’t be stored in an integer variable.

Output:

main.cpp: In function 'int main()': main.cpp:7:7: error: invalid conversion from 'int*' to 'int' [-fpermissive] ptr = &p; //invalid conversion. ^

Resolve the Conversion Error

Most compilers don’t allow a type casting from pointer type to the simple datatype. Therefore, the issue can be solved by ensuring that the address type value is assigned to a proper pointer variable.

Example Code:

#include <iostream>
using namespace std;

int main() {
  int a = 10;
  int* p;
  p = &a;
  cout << p;
}

Run Code

The * symbol while declaring p will make it a pointer to an integer. Thereby making it capable of storing the address of an integer variable without requiring any type-conversions.

Related Article - C++ Error