cout fails to print the address of a null char pointer?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • zackp

    cout fails to print the address of a null char pointer?

    Hello,

    I am learning C++ lately. This morning, out of curiosity I
    constructed a simple code below, but to my surprise, when char* is
    used, the program fails to print almost anything.
    The only thing I got is the following:

    % [0]: np =

    As soon as I use a pointer to another type, everything behaves as
    anticipated. This is a really trivial code, but I am completely
    puzzled. Any hints are appreciated.

    Compiler: gcc version 3.4.2
    Environment: a Dell 1450 laptop running SUN Solaris 10 intel

    Thanks,

    --Zack
    ---------------------------------------- The test code
    ------------------------------------------
    #include <iostream>
    #include <string>

    using std::cout;
    using std::endl;
    using std::string;

    int main(void)
    {
    // if string* is changed to char*, then the program no longer
    prints
    //string* np = 0;
    //string** pnp = &np;
    // should figure out the reason w
    char* np = 0;
    char** pnp = &np;
    cout << "[0]: np = " << np << endl;
    cout << "[1]: pnp = " << pnp << endl;
    cout << "Why the above statements not printing?" << endl;
    return 0;
    }
  • acehreli@gmail.com

    #2
    Re: cout fails to print the address of a null char pointer?

    On Aug 5, 1:22 pm, zackp <zack.pe...@sbc global.netwrote :
        // if string* is changed to char*, then the program no longer
    prints
        //string* np = 0;
        //string** pnp = &np;
        // should figure out the reason w
        char* np = 0;
        char** pnp = &np;
        cout << "[0]: np = " << np << endl;
    operator<< on ostream is overloaded for char* type and will follow the
    pointer to print the characters in that C-style string. You must not
    pass use the null pointer in that case.

    If you want to print the pointer value, then cast it to void* first
    (which is 0 in this case):

    cout << "[0]: np = " << static_cast<voi d*>(np) << endl;
        cout << "[1]: pnp = " << pnp << endl;
    No problem with that one, because it is the address of np and is not
    NULL.

    Ali

    Comment

    Working...