c - 在字符串中不使用空终止会产生什么影响?

标签 c string char

以下面的代码为例:

int main(){
    char string[] = { 'h' , 'e', 'l', 'l', 'o' };
    printf(string);
    printf("\n%d", strlen(string));
}

输出将是:

hello
6

所以一开始我就可以看到 strlen 值减少了 1,但如果我们考虑到它,它似乎并不是一个障碍。

什么时候不终止字符串会产生问题?

最佳答案

What are the repercussions of not using null termination in strings?

技术上没有,因为 C 字符串是 - by definition - 以空字符终止:

A string is a contiguous sequence of characters terminated by and including the first null character.

所以如果它没有正确终止,它就不是一个字符串。

如果将字符串传递给需要字符串的代码,则会调用未定义的行为。

关于c - 在字符串中不使用空终止会产生什么影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52720975/

相关文章:

c - 如何打印命令行 C 上的内容

Python .format 切片长字符串并添加点

c - 使用 C 返回数组

c++ - 使用中文字符时文件名错误

c - 如何在 C 中将 char(*)([long unsigned int]) 作为参数传递?

java - c - 客户端/java - 服务器 - 客户端读取奇怪的东西

c - 绕 Y 轴旋转 gluLookAt

子进程执行 fork 调用之前写的语句

javascript - 如何在 JavaScript 中将 xml 存储为字符串变量?

c# - 有没有办法检查一个字符串是否不等于多个不同的字符串?