Warning: Cast From Integer to Pointer of Different Size in C++

In C++, pointers stores memory address as its value. Integers, on the other hand, hold numerical values. When we attempt to convert the value of integer to pointer directly, especially when the memory that is allocated to a pointer is smaller than the memory allocated to an integer data type, the compiler might issue the warning: “Cast From Integer to Pointer of Different Size”. In this article, we will learn how to avoid this warning in C++.

What is “Cast From Integer to Pointer of Different Size” Warning?

In C++, the compiler issues a warning when something is off or wrong in the code. The warning: cast from integer to pointer of different size is issued by the compiler when we try to save the value of some integer variable to pointer directly without considering the size differences. This conversion is considered wrong due to the following reasons:

  • In C++, pointers are used to store memory addresses only, we cannot forcefully store the value of integer variables in it. Although, we can store the address of that variable in the pointer but not the value directly.
  • The size of the pointer and integer in C++ are both different, which may cause a loss of information due to typecasting between incompatible types.

For example, the below program generates the warning of cast from integer to pointer of different size due to casting an integer variable to pointer:

C++
// C++ program to demonstrate warning: cast from integer to
// pointer of different size

#include <iostream>
using namespace std;

int main()
{
    // define an integer variable num
    int num = 500;

    // defining a pointer of type integer
    int* myptr;
    // trying to asign value of integer varible num directly
    // to pointer, this conversion is wrong
    myptr = num;

    return 0;
}


Output

./main.cpp:16:13: error: incompatible integer to pointer conversion assigning to 'int *' from 'int'; take the address with &
    myptr = num;
            ^~~

How to Resolve Warning: Cast From Integer to Pointer of Different Size

To resolve the warning, make sure that you are using the correct data type for the variable. For pointer to int conversion, use the type uintptr_t that is defined inside <cstdint> libarary. It is guaranteed to be of the same size of that of the pointer in the given system.

C++
// C++ program to demonstrate how to avoid warning: cast
// from integer to
// pointer of different size
#include <cstdint>
#include <iostream>

using namespace std;

int main()
{
    int var = 10;
    int* ptr = &var;

    // Correctly using uintptr_t and safely
    // casting ptr
    uintptr_t address = reinterpret_cast<uintptr_t>(ptr);

    cout << ptr << endl;
    return 0;
}

Output
0x7fff9ad91e8c