关于C语言中字符串以‘\0‘结尾的原因

‘\0’一般放在字符串的结束处,用来表示字符串的结束,其是ascii值为0的字符的转义。如果一个字符串中没有’\0’这个结束字符,那么这些函数将不能确定字符串的结束位置在哪儿,从而引起一些不必要的错误。

在C++中,string类型的实现也是字符数组,其结尾也是以’\0’填充,用来表示字符串的结束位置。

以下是测试函数,在字符数组结尾添加和不添加‘\0’,进行输出:

#include <stdio.h>
using namespace std;
int main() {
    
    
    char s[2];
    s[0] = '1';
    s[1] = '\0';
    printf("s = %s\n", s);

    char t[2];
    t[0] = '1';
    //t[1] = '\0';
    printf("t = %s\n", t);

    return 0;
}

函数输出:

s = 1
t = 1烫烫烫烫烫?

很明显看到,如果字符数组结尾没有用‘\0’表示,那么在读取的时候,将无法找到其结束位置,可能将其后的空间数据也进行打印,进而产生错误。

平时当我们在创建一些常量字符串的时候,其末尾也是默认添加’\0’的,不用我们去手动添加。比如,可以做以下测试:

#include <iostream>
#include <string>
using namespace std;
int main() {
    
    
    string s = "12131";
    if (s[5] == '\0') {
    
    
        cout << "yes" << endl;
    }
    return 0;
}

函数输出:

yes

根据输出,我们确定常量字符串末尾是以’\0’结束的。

谢谢阅读。

猜你喜欢

转载自blog.csdn.net/weixin_43869898/article/details/110135668