我在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;
}
Run Code Online (Sandbox Code Playgroud)
当我们没有用null字符显式初始化字符数组时,字符串的长度是多少?
字符串的长度是它包含的字符数.(为简单起见,我们忽略了这样一个事实,即字形数,代码点和代码单元之间存在差异,所有这些都是字符串的长度,具体取决于透视.在这个答案的上下文中,字符==代码单元).
空终止字符串的长度是空终止符之前的字符数.如果字符串不包含空终止符,则它不是以空字符结尾的字符串.
Run Code Online (Sandbox Code Playgroud)strlen(b)
b不是以空字符结尾的字符串.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)
Run Code Online (Sandbox Code Playgroud)
在任何程序中都不希望出现未定义的行为.
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |