为什么c++字符数组中的这个null终止未被识别

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

本文关键字:终止 null 识别 字符 c++ 数组 为什么      更新时间:2024-09-29

我有一个非常简单的C++代码,如下所示:

#include <iostream>
using namespace std;
int count_occurrences(char *pc, char c) {
int count = 0;
while (pc != '') {
if (*pc == c) {
++count;
}
++pc;
}
return count;
}
int main() {
char v[6] {'h', 'e', 'l', 'l', 'o', ''}; 
cout << "Total occurence of  'a'" << count_occurrences(&v[0], 'l');
}

char数组以null结尾,但while (pc != '')无法检测到放置在字符数组末尾的null。我试过while (pc != NULL)while (pc != nullptr),但没有成功。

尝试检查这个

while(*pc != '')