为什么必须使用空终止符? [英] Why is a null terminator necessary?
问题描述
最近几天,我一直在自学c ++,为我作为CS专业的大一新生做准备.我现在正在使用C风格的字符串,想知道null终止符的意义是什么.
I've been teaching myself c++ for the last couple days to prepare for my freshman year as a CS major. I'm on C-style strings right now, and wondering what the point of a null terminator is.
我知道这是必要的,但我想我只是从根本上不理解为什么一个字符串不会仅仅以其最后一个字符结尾.
I understand that it's necessary, but I guess I just don't fundamentally understand why a string wouldn't just end on its last char.
推荐答案
我只是从根本上不理解为什么一个字符串不会仅仅以其最后一个字符结尾.
I just don't fundamentally understand why a string wouldn't just end on its last char.
有几种方法可以知道最后一个字符"在哪里:
There are several ways of knowing where is the "last char":
- 将字符串中的字符数与字符串的字符分开存储,
- 放置标记以指示字符串的最后一个字符,或者
- 将指针的最后一个字符与字符串的字符分开存储.
C选择第二条路线;其他语言(帕斯卡等)选择第一条路线.C ++ std :: string
的某些实现选择第三条路由 * .
* 甚至使用第一种或第三种方法的
std :: string
实现也以空值终止其缓冲区,以与库的C部分兼容.必须确保 c_str()
返回有效的C字符串.
C choose the second route; other languages (Pascal, etc.) choose the first route. Some implementations of C++ std::string
choose the third route* .
* Even
std::string
implementations that use the first or the third approach null-terminate their buffers for compatibility with the C portions of the library. This is necessary to ensure that c_str()
returns a valid C string.
这篇关于为什么必须使用空终止符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!