为什么char数组必须以空字符结尾

为什么char数组必须以空字符结尾

本文介绍了为什么char数组必须以空字符结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么char array必须以空字符结尾?我有什么理由要向每个char数组中添加空字符吗?

Why does a char array have to end with a null character? Is there any reason that I have to add the null character to to every char array ?

似乎他们得到了相同的对待.

It seems that they get treated the same way.

推荐答案

在C语言中,如果您有一个指向数组的指针,则无法确定该数组的长度.正如@AProgrammer指出的那样,设计人员可能已将其留在此处,并迫使程序员跟踪所有字符数组的长度.但是,这会使C语言中的文本处理比以前更加困难.

In C, if you have a pointer to an array, then there is not way to determine the length of that array. As @AProgrammer points out, the designers could have left it at that and forced the programmer to keep track of the length of all character arrays. However, that would have made text processing in C even harder than it already is.

因此,语言设计者决定采用一种约定,该约定允许通过指示字符串结尾的空字符来推断字符串的长度.

Therefore the language designers settled on a convention that would allow string length to be inferred by the presence of a null character indicating the end of the string.

例如,考虑strcpy:

char *strcpy(char *destination, const char *source);

在C中无法确定指针destinationsource指向的数组的长度.因此,在不存在指示字符串结尾的标记值的情况下,唯一的解决办法是传递额外的参数来指示source字符串的长度.

There is no way in C to determine the length of the array that the pointers destination and source point to. So, without the presence of a sentinel value to indicate the end of the string, the only other solution would have been to pass extra parameters indicating the length of the source string.

当然,考虑到现代安全性,已经引入了接收缓冲区长度参数的字符串处理功能.但是,在发明以空值终止的字符串时,计算环境看起来大不相同.

Of course, in light of modern security considerations, string processing functions that receive buffer length parameters have been introduced. But the computing landscape looked very different at the time that the null-terminated string was invented.

这篇关于为什么char数组必须以空字符结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:36