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

Z

zackp

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;
}
 
A

acehreli

    // 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 said:
    cout << "[1]: pnp = " << pnp << endl;

No problem with that one, because it is the address of np and is not
NULL.

Ali
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top