Question

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;
}
Was it helpful?

Solution 2

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;

OTHER TIPS

When you pass a char * pointer to the << operator of std::cout, it prints the string that the pointer points to, not the address. It's the same behavior as the following code:

const char *str = "Hello!";
cout << str; // Prints the string "Hello!", not the address of the string

In your case, p0 doesn't point to a string, which is why you're getting unexpected behavior.

As others have said cout is interpreting the char* as a string, and not a pointer

If you wanted to prove that the address is the same whatever type of pointer it is then you can cast it to a void pointer

cout<<(void*)p0<<endl;

In fact you get the address for pretty much any type other than char&

cout<<(float*)p0<<endl;

To prove to yourself that a char* pointer would have the same value use printf

printf("%x", p0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top