2

My IDE is Xcode. The following code can not run as expected. Though nullptr is recommended in newer standard of C++.

#include<iostream>
using namespace std;

int count_x(char * p, char x)
{
    if(p==nullptr)return 0;
    int count = 0;
    for (; p!=nullptr; ++p)
        if(*p == x)
            ++count;

    return count;
}

int main()
{
    char str[] = "I'm a little girl in the little world!";

    cout<<"number of t in the string is "<<count_x(str, 't')<<"\n";
}

/*
 the expected output is:

 number of t in the string is 5
 Program ended with exit code: 0

*/

The code above can be compiled successfully, but when I ran it, I can not get expected output. In debug mode, I figured out that the for loop did not stop. So I change the code into the following one:

#include<iostream>
using namespace std;

int count_x(char * p, char x)
{
    if(p==nullptr)return 0;
    int count = 0;
    for (; *p!='\0'; ++p)
        if(*p == x)
            ++count;

    return count;
}

int main()
{
    char str[] = "I'm a little girl in the little world!";

    cout<<"number of t in the string is "<<count_x(str, 't')<<"\n";
}

/*
 the expected output is:

 number of t in the string is 5
 Program ended with exit code: 0

*/

After I changed p!=nullptr into *p!='\0', the code worked fine and expected output was got. Though code seems working, I still don't understand the reason for failure or success.

Could you give me some clues or suggestions? Thanks.

f1chen
  • 121
  • 5

3 Answers3

3

The only difference is change nullptr into '\0'.

There is another difference:

 p!=nullptr
*p!='\0'
^
|
+---- right here, a dereference operation

I still don't understand the reason for failure ...

I figured out that the for loop did not stop

Your condition is to stop when the value of p is nullptr (i.e. zero). But you only ever increment p, so how could it ever reach zero? It won't ever reach zero before you have overflown the string.

I still don't understand the reason for ... success.

In your successful attempt the end condition is not to compare the pointer, but to compare the pointed value to the null termination character. This works as long as the character string is null terminated.


Additional note: Even though both the null pointer and the null character have the same name (null), and the same value (0), they have different types and are separate concepts.

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • so is it possible to change char str[ ] = "I'm a little girl in the little world!", then the count_x can work? – f1chen Mar 27 '17 at 11:36
  • because the count_x is the sample code from the book "A tour of C++" – f1chen Mar 27 '17 at 11:37
  • @f1chen why would changing the string make the function work? The first function won't work correctly with any string. Double check that you didn't misread. If there is an error in your book, look for the errata on the publishers website, and if the error is not corrected, then consider informing the publisher. – eerorika Mar 27 '17 at 11:40
  • thanks for your suggestion. On author's website, I've found the errors and clarifications. – f1chen Mar 27 '17 at 12:50
2

Type of nullptr is std::nullptr_t. It is generic pointer literal that can convert to any type
Type of '\0' is char. It is used in C-style string for marking string termination.
Both may be same value on your platform but are different types. It is bad to compare for example 0 km to 0 kg.


Now the real problem in your code is p == nullptr. You can't expect the pointer to become nullptr (start pointing to nothing) by just incrementing.

The only difference is change nullptr into '\0'.

No you also changed p to *p.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • thanks for your notification. Yes, I changed p!=nullptr into *p!='\0'. – f1chen Mar 27 '17 at 11:04
  • "It was used in C functions" well, it *is* still used both in C and C++ functions that deal with NUL-terminated strings. – Matteo Italia Mar 27 '17 at 11:06
  • String stored in char array, '\0' would be added at the end. The count_x function is a sample code from the book "A Tour of C++",which uses p!=nullptr. I add a main function to call the count_x, but the for loop can't stop. I don't why:( – f1chen Mar 27 '17 at 11:08
  • @f1chen The book uses the nullptr check to make sure you passed a valid argument to the function. The loop condition still uses `*p != 0` (mind the leading `*`), so the code from the book is correct. (FYI: An early draft of that chapter is available for [free online viewing on isocpp.org](https://isocpp.org/images/uploads/2-Tour-Basics.pdf)). – ComicSansMS Mar 27 '17 at 11:16
0

Consider

int test = NULL;

and

int *test = NULL;

Both above code will be able to work. (Although the first line above will say some warning about “Converting from NULL to non-pointer type”

However,

nullptr is really a “null pointer” and always a pointer. If you try assigning it to integer. It will cause an error

int test = nullptr;

But it will work if it’s

int *test = nullptr;
ashish bansal
  • 411
  • 7
  • 19