我在GNU GCC编译器上尝试了以下代码,并给出了26的输出。但是我不明白代码的工作方式,尤其是 strlen()函数的实际作用。>
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
char b[]={'G','E','E','K','S',' ','F','O','R',' ','F','U','N'};
cout<<sizeof(b)<<endl;
cout<<strlen(b)<<endl;
return 0;
}
答案 0 :(得分:6)
当我们不显式初始化带有空字符的字符数组时,字符串的长度是多少?
字符串的长度是它包含的字符数。 (为了简单起见,我们忽略了字素,代码点和代码单位的数量之间存在差异的事实,所有这些都是视角度而定的字符串的长度。在此答案的上下文中,字符==代码单位)。
以 null结尾的字符串的长度是null终止符之前的字符数。如果字符串不包含空终止符,则它不是空终止字符串。
strlen(b)
b
不是以null结尾的字符串。 strlen
要求参数指向以null结尾的字符串。如果不满足要求,则程序的行为是不确定的。
但是它的工作方式除了给出o / p 13之外,它给出26的输出
该行为是不确定的。可能的行为包括,但不能保证以下任何一种行为:
- working
- not working
- random output
- non-random output
- the expected output
- unexpected output
- no output
- any output
- crashing at random
- crashing always
- not crashing
- corruption of data
- different behaviour, when executed on another system
- , when compiled with another compiler
- , on tuesday
- , only when you're not looking
- same behaviour in all of the above cases
- anything else within the power of the computer (hopefully limited by the OS)
未定义行为在任何程序中都是不可取的。
答案 1 :(得分:4)
但是我不明白代码是如何工作的,尤其是strlen()函数的实际作用。
当您将一个不以null终止的字符串传递给strlen
时,您正在调用未定义的行为。不要指望任何可预测的行为。
答案 2 :(得分:0)
字符串长度或strlen
表示C字符串,该字符串的长度与字符串开头和终止空字符之间的字符数一样长(不包括终止空字符本身)。
例如:
char TestStr[25] = "Test String";
如果您使用sizeof(TestStr)
,它将评估数组中的25个字符,而使用strlen(TestStr)
将仅评估11个字符。
希望这会有所帮助
答案 3 :(得分:0)
与您的问题有关的另一种情况:
int main()
{
static const char fun_text[] = {'f', 'u', 'n', '\0', 'c', 'a', 's', 'e'};
std::cout << strlen(fun_text) << std::endl;
std::cout << sizeof(fun_text) << std::endl;
return 0;
}
在上述情况下,数组大小为8。
但是,strlen
函数将返回3,因为它在到达数组末尾之前遇到了'\0'
字符。
strlen
函数根据内容返回长度。
sizeof
运算符返回数组的长度,而与内容无关。