currently I am reading "A tour of C++" by Byarne Stroustrup. The thing that matters: on "pointers, arrays and references" he gave an example about using nullptr
like this:
int count_x(char* p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
if (p == nullptr) return 0;
int count = 0;
for (; p != nullptr; ++p)
if (*p == x)
++count;
return count;
}
In my my main:
int main(){
char* str = "Good morning!";
char c = 'o';
std::cout << count_x(str, c) << std::endl;
return 0;
}
When I run the program it crashes I get an exception thrown at line
if (*p == x)
If I change the loop to be like this:
for (; *p; p++)
if (*p == x)
++count;
Now everything works fine! I am using MSVC++ 14.0.
- The same code I ran on
ideone
I don't get an exception but the result is always0
which should be3
: