在C字符串为什么要为空结束的? [英] Why do strings in C need to be null terminated?

查看:169
本文介绍了在C字符串为什么要为空结束的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道为什么是这样的情况。我渴望更多地了解低级的语言,我只是为C的基础知识,这已经是困惑我。

Just wondering why this is the case. I'm eager to know more about low level languages, and I'm only into the basics of C and this is already confusing me.

不喜欢PHP语言自动终止空,因为他们正在串间preTED和/或解析?

Do languages like PHP automatically null terminate strings as they are being interpreted and / or parsed?

推荐答案

从的话题乔尔的优秀文章:

记住的方式串用C的工作:它们由一堆字节后跟一个空字符,其值为0。这有两个明显影响:

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:

有没有办法知道那里的字符串结尾(即字符串的长度),而无需通过其移动,寻找末尾的空字符。
  您的字符串不能有任何的零在里面。所以,你不能存储任意的二进制BLOB像一个C字符串中的JPEG图片。
  为什么C字符串以这种方式工作?这是因为PDP-7的微处理器,其上UNIX和C编程语言被发明,有一个ASCIZ字符串类型。 ASCIZ意味着ASCII,并在最后一个Z(零)。

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."

这是存储字符串的唯一途径?没有,事实上,它是存储字符串最坏的方法之一。对于非平凡的程序,应用程序接口,操作系统,类库,你应该避免ASCIZ串像瘟疫。

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字符串为什么要为空结束的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆