1

I have a very simple C++ code like so:

#include <iostream>
using namespace std;

int count_occurrences(char *pc, char c) {
    int count = 0;
    while (pc != '\0') {
        if (*pc == c) {
            ++count;
        }
        ++pc;
    }
    return count;
}

int main() {
    char v[6] {'h', 'e', 'l', 'l', 'o', '\0'}; 
    cout << "Total occurence of  'a'" << count_occurrences(&v[0], 'l');
}

The char array is null terminated, however the while (pc != '\0') is not able to detect the null placed at the end of the character array. I have tried while (pc != NULL) and while (pc != nullptr) but no luck.

6
  • 8
    while(*pc != '\0') Commented May 18, 2021 at 11:15
  • if warnings switched on, it should have at minimum one! Commented May 18, 2021 at 11:17
  • Try this while (*pc) Commented May 18, 2021 at 11:22
  • 2
    I think you're confusing the null character ('\0') with the null pointer. A pointer to the null character is not the same thing as a null pointer. Commented May 18, 2021 at 11:38
  • 1
    @sshekhar1980 You should consider upgrading your compiler. GCC 5 was released 6 years ago. Commented May 18, 2021 at 11:40

1 Answer 1

2

try to check this out this

while(*pc != '\0')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.