Strlen返回不合理的数字 [英] Strlen returns unreasonable number
问题描述
如果我写:
char lili [3];
cout<<strlen(lili)<<endl;
那么打印的是:11
但是如果我写:
char lili [3];
lili [3]='\0';
cout<<strlen(lili)<<endl;
那么我得到3。
不理解为什么它在第一部分返回11?
不是strlen应该返回3,因为我为 lili
分配了3个字符?
I don't understand why it returns 11 on the first part?
Isn't strlen supposed to return 3, since I allocated 3 chars for lili
?
推荐答案
这是因为 strlen
终止字符串。如果你给它一个简单的指针或未初始化的缓冲区,如你在第一个例子中,它将继续前进通过内存,直到它a)找到一个 \0
,在这一点它会返回那个字符串的长度,或b)直到它到达受保护的内存位置并产生错误。
It is because strlen
works with "C-style" null terminated strings. If you give it a plain pointer or uninitialised buffer as you did in your first example, it will keep marching through memory until it a) finds a \0
, at which point it will return the length of that "string", or b) until it reaches a protected memory location and generates an error.
由于你已经标记了这个C ++,也许你应该考虑使用 std :: array
或更好, std :: string
。两者都提供长度返回函数( size()
),并且都有一些额外的范围检查逻辑,这将有助于防止你的代码漫游到未初始化的内存区域。
Given that you've tagged this C++, perhaps you should consider using std::array
or better yet, std::string
. Both provide length-returning functions (size()
) and both have some additional range checking logic that will help prevent your code from wandering into uninitialised memory regions as you're doing here.
这篇关于Strlen返回不合理的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!