JuanPablo JuanPablo - 24 days ago 6
C++ Question

Stop a while with nullptr in c++

I try to use nullptr in a while, if is the null pointer stop while.

#include <iostream>

using namespace std;

int count_x(char* p, char x)
{
int count = 0;
while(p)
{
if (*p==x)
++count;
++p;
}
return count;
}

int main(int argc, char *argv[])
{
char *arr = "aabbaa";
char s = 'a';
cout << count_x(arr, s) << endl;
return 0;
}


but with this code, When I execute I get this message

Bus error: 10


I compile with this line

g++ -std=c++11 -o count_x count_x.cpp

Answer

The string is zero-terminated, which means, that its last byte is 0. If you increase the pointer, you need to check for the pointer pointing to 0, not beeing 0.

#include <iostream>

using namespace std;

int count_x(char* p, char x)
{
    int count = 0;
    while (*p)
    {
        if (*p == x)
            ++count;
        ++p;
    }
    return count;
}

int main(int argc, char *argv[])
{
    char *arr = "aabbaa";
    char s = 'a';
    cout << count_x(arr, s) << endl;
    return 0;
}