Output of char * Variable

(from http)
A character string is of type char *. Suppose we want to print the value of that pointer,i.e., the memory address of the first
character of that string. But the << operator has been overloaded to print data of type char* as a null-terminated string.
The solution is to cast the pointer to void * (this should be done to any pointer variable the programmer wishes to output as an address.)


#include<iostream>
using namespace std;
int main()
{
    char *string = "test";
    cout << &string << endl; //what is &string? --the address of the pointer?
    cout << *string << endl; //print the first letter
    cout << *string +1<< endl;  // print an integer 117 which represents letter "u"
    cout << static_cast<char>(*string + 1) << endl; // print the letter "u" next to "t" in the alphabet
    cout << *(string +1) << endl; //pint the second letter
    //print the string
    cout << "Value of string is: " << string ;
    //print the address of the first letter in the string
    cout        << "\nValue of static_cast<void*>(string) is: "
           << static_cast<void *>(string) << endl;
    int a = 10;
    int * pt = &a;
    cout << endl <<  "pt =  " << pt <<  endl;
    cout << "*pt = a = " << *pt << endl;
    cout << "&a = " << &a << endl;
    cout << "&pt = " << &pt << endl;
    //print the address of  the integer a;
    cout << "static_cast<void *>(pt) is " << static_cast<void *>(pt) << endl;
    return 0;
}
Capture

No comments: