簡體   English   中英

為什么無法識別 c++ 字符數組中的此 null 終止

[英]Why is this null termination in c++ char array not recognized

我有一個非常簡單的 C++ 代碼,如下所示:

#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');
}

字符數組是null終止的,但是while (pc != '\0')無法檢測到放置在字符數組末尾的 null。 我試過while (pc != NULL)while (pc != nullptr)但沒有運氣。

試試看這個

while(*pc != '\0')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM