0
#include<iostream>
using namespace std;

int main(){
    int a=1025;

    int *p=&a;
    cout<<"Size of integer is: "<<sizeof(int)<<" bytes"<<endl;
    cout<<"Address= "<<p<<" Value= "<<*p<<endl;

    char *p0;
    p0=(char*)p;
    cout<<"Size of char is: "<<sizeof(char)<<" bytes"<<endl;
    cout<<"Address= "<<p0<<"Value= "<<*p0<<endl;
    cout<<"It printed smilie above";

    return 0;
}

Why is the address and value of char printed as a smilie?

The output I got is:

Size of integer is: 4 bytes  
Address= 0x61ff04 Value= 1025
Size of char is: 1 bytes     
Address= ☺♦Value= ☺
JaMiT
  • 14,422
  • 4
  • 15
  • 31

1 Answers1

1

The overload for operator<< which prints char* (like char *p0;) does not print the address the pointer is pointing at like the overload for void*. Instead, it actually reads the content at the pointed-out address - and keeps on reading, until a \0 is encountered, which is what makes std::cout << "Hello world"; work.

"Hello world" (a null terminated C string) in itself decays into a const char*, pointing at the H, and the operator<< overload starts reading there and outputs each character until it sees a \0 and then it stops.

The smiley is just a happy coincidence. The values stored at the pointed-out address happened to form a unicode sequence - which forms a smiley.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108