Search code examples
c++pointerstypecasting-operator

How to: Typecasting Pointers on c++


I am learning typecasting.

Here is my basic code, i dont know why after typecasting, when printing p0, it is not showing the same address of a

I know this is very basic.

#include <iostream>
using namespace std;

int main()
{
    int a=1025;
    cout<<a<<endl;
    cout<<"Size of a in bytes is "<<sizeof(a)<<endl;

    int *p;//pointer to an integer
    p=&a; //p stores an address of a
    cout<<p<<endl;//display address of a
    cout<<&a<<endl;//displays address of a
    cout<<*p<<endl;//display value where p points to. p stores an address of a and so it points to the value of a

    char *p0;//pointer to character
    p0=(char*)p;//typecasting
    cout<<p0<<endl;
    cout<<*p0;

    return 0;
}

Solution

  • The overload of operator<<, used with std::cout and char* as arguments, is expecting a null-terminated string. What you are feeding it with, instead, is a pointer to what was an int* instead. This leads to undefined behavior when trying to output the char* in cout<<p0<<endl;.

    In C++, is often a bad idea to use C-style casts. If you had used static_cast for example, you would have been warned that the conversion your are trying to make does not make much sense. It is true that you could use reinterpret_cast instead, but what you should be asking yourself is: why am I doing this? Why am I trying to shoot myself in the foot?

    If what you want is to convert the number to string, you should be using other techniques instead. If you just want to print out the address of the char* you should be using std::addressof:

    std::cout << std::addressof(p0) << std::endl;