Strlen returns unreasonable number

耗尽温柔 提交于 2020-01-10 05:46:11

问题


If I write:

char  lili [3];
cout<<strlen(lili)<<endl;

then what is printed is : 11

but if I write:

char  lili [3];
lili [3]='\0';
cout<<strlen(lili)<<endl;

then I get 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?


回答1:


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.

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.




回答2:


The strlen function searches for a byte set to \0. If you run it on an uninitialized array then the behavior is undefined.




回答3:


You have to initialize your array first. Otherwise there is random data in it.

strlen is looking for a string termination sign and will count until it finds it.




回答4:


strlen calculates the number of characters till it reaches '\0' (which denotes "end-of-string"). In C and C++ char[] is equivalent to char *, and strlen uses lili as a pointer to char and iterates the memory pointed to by it till it reaches the terminating '\0'. It just so happened that there was 0 byte in memory 11 bytes from the memory allocated for your array. You could have got much stranger result.

In fact, when you write lili[3] = '\0' you access memory outside your array. The valid indices for 3-element array in C/C++ are 0-2.



来源:https://stackoverflow.com/questions/11222613/strlen-returns-unreasonable-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!