Aren't pointers supposed to point to nullptr when an array ends?

Viewed 126

Why does this code not work?, I used the function from "A Tour of C++" and it tells me that pointers point to nullptr when an array ends briefly explained. I tried to implement it and it doesn't show anything. Thanks in advance.

#include <iostream>

int count_x(char* p, char x)
{
    int count = 0;
    while (p) 
    {
        if (*p == x){++count;}
        p++;
    }
    return count;
}
 
int main()
{
    char my_string[] {"hello world"};
    char* my_string_ptr {my_string};

    std::cout << "There are " << count_x(my_string_ptr,'a') << " a in the string\n";

    return 0;

}``` 
3 Answers

No, pointer at the end of an array are not null. You probably want:

while (*p) 

which is the same as

while (*p != '\0')

and

while (*p != 0)

which are testing for the null character.

p stores an address value in the computer memory which is deferenced by astricks (*) like *p. In your code,

p++;

is incrementing the current address to which the p is pointing currently. When you reach the end of the string (at the last null character), p will be the address of the null character not the null itself, so

while(p)

will be true and following p++ will increment it to next memory location (which technically does not belong to the allocated string), and hence p will return non-zero address this while loop will keep on running and you will get a segmentation fault.

As the jeffrey has mentioned in his answer too, use *p to test the while condition so when p reaches the null, it can derefer it.

Your original code crashed (or caused segmentation fault). The reason is that in the while loop, you did not correctly specify the condition to exit this while loop. Therefore, the while loop will continue to go past the end of the string, which causes segmentation fault (i.e, your app will crash).

One correct way to exit the while loop is to compare each character of the string to see if that character equals the end of string character that is '\0'.

When you encounter this end of string character that is '\0', you should exit the while loop.

I have fixed one line of your code, and your function is now working fine as shown below:

int count_x(char* p, char x)
{
    int count = 0;
    
    while (*p != '\0')   // I fixed your code here
    {
        if (*p == x){++count;}
        p++;
     
    }
    return count;
}

Again, please note that the code above runs well, and produces the correct result as I have verified it. Please let me know if you run into any issue. Cheers.

Related