0

This is the continnum of atoi() method, char * cout

The last question I don't understand is:

After line 5,

    while ( pCur >= pStr && *pCur <= '9' && *pCur >= '0' )     {       

Now pCur = 2 and pStr = 242, why the condition is evaluated to be true?

I actually wrote the cout test:

    cout << "pCur: " << pCur << endl;       //line 5
    cout << "pStr: " <<  pStr << endl;  
    bool b = (pCur >= pStr);
    cout << "pCur >= pStr: " << b << endl;

Output:

pCur: 2    
pStr: 242
pCur >= pStr: 1

This doesn't make any sense to me.

Community
  • 1
  • 1
HoKy22
  • 4,057
  • 8
  • 33
  • 54

1 Answers1

0

pCur and pStr are both char*. A char* is often understood as being a C-style string, because it might (and often does) point at the first character in a null-terminated array of char. When you do cout << pCur, the output stream cout interprets it as a C-style string and prints out the characters that it points at. If you want to print out the actual pointer values, try this:

cout << "pCur: " << static_cast<void*>(pCur) << endl;
cout << "pStr: " << static_cast<void*>(pStr) << endl; 

The cast to a void* stops cout from treating it as a C-style string. I bet you'll now find that pCur >= pStr as expected.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • Ohh I got it, but how does the compiler know what I meant to be pCur or static_cast(pCur)? In this while loop, the compiler seems to interpret it as static_cast(pCur) even though pCur was used – HoKy22 Mar 04 '13 at 23:03
  • @HoKy22 Most everything you do to a `char*` will treat it as a pointer - because that's what it is. A `char*` really isn't special in any way. It's just a pointer. Some parts of the C++ library treat it differently. Most obviously, the input/output library has special overloads for functions to treat a `char*` as a C-style string. – Joseph Mansfield Mar 04 '13 at 23:04