gpt4 book ai didi

c - 为什么 C 中的字符串需要以 null 终止?

转载 作者:太空狗 更新时间:2023-10-29 16:28:16 25 4
gpt4 key购买 nike

只是想知道为什么会这样。我渴望了解更多关于低级语言的知识,而我只了解 C 的基础知识,这已经让我感到困惑。

像 PHP 这样的语言是否会在解释和/或解析字符串时自动以 null 终止字符串?

最佳答案

来自 Joel's excellent article on the topic:

Remember the way strings work in C: they consist of a bunch of bytes followed by a null character, which has the value 0. This has two obvious implications:

There is no way to know where the string ends (that is, the string length) without moving through it, looking for the null character at the end. Your string can't have any zeros in it. So you can't store an arbitrary binary blob like a JPEG picture in a C string. Why do C strings work this way? It's because the PDP-7 microprocessor, on which UNIX and the C programming language were invented, had an ASCIZ string type. ASCIZ meant "ASCII with a Z (zero) at the end."

Is this the only way to store strings? No, in fact, it's one of the worst ways to store strings. For non-trivial programs, APIs, operating systems, class libraries, you should avoid ASCIZ strings like the plague.

关于c - 为什么 C 中的字符串需要以 null 终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2221304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com