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.