为什么字节长度是这样算的啊while (*(string + i)!=NULL)


#include <iostream>
using namespace std;
int str_len(const char* string)
{
   
    int i = 0;
    while (*(string + i)!=NULL)
        i++;
    return i;
}

void main()
{
    char a[] = "ABCDE";
    cout << a << "\t" << str_len(a) << endl;
    const char* str = "Hello!";
    cout << str << "\t" << str_len(str) << endl;
    cout << "This is a test." << "\t" << str_len("This is a test.") << endl;

}

就相当于string[i]!=NULL 如果不等于就继续循环下去
string[i]是数组元素,然后从i=0,开始string[0]!=NULL,然后i++计数,就像这样一直循环到为空的元素空间,也就计算成功了。

希望对题主有所帮助,可以的话,帮忙点个采纳!

这就是循环寻找字符串的结束符,找到结束符时,循环次数i就是字符串长度了。