[英]How is the strlen calculated for a string without null character?
This code returns n=11, with 10th and 11th character as ' ' and '@' How does this work? 此代码返回n = 11,第10个和第11个字符为''和'@'这是如何工作的? How does strlen function take it as 11 characters? strlen函数如何将其视为11个字符? It seems like it takes the string length as 12 characters in some compilers. 在某些编译器中,似乎需要字符串长度为12个字符。
#include <stdio.h>
#include <string.h>
void fun(char *arr)
{
int i;
unsigned int n = strlen(arr);
printf("n = %d\n", n);
for (i=0; i<n; i++)
printf("%c ", arr[i]);
}
int main()
{
char arr[] = {'g', 'e', 'e', 'k', 's', 'q', 'u', 'i', 'z'};
fun(arr);
return 0;
}
According to standard, since your "string" does not have null terminator, this is not a string. 根据标准,由于您的“字符串”没有空终止符,因此这不是字符串。 Calling strlen
with anything but string is undefined behavior, so anything can happen including the case you're observing. 使用除字符串之外的任何内容调用strlen
是未定义的行为,因此任何事情都可能发生,包括您正在观察的情况。
If you wonder, how exactly this is happening, this is likely because of strlen
keeps trying to find null terminator, and occasionally finds it in memory somewhere after the arr
. 如果你想知道,究竟是怎么回事,这很可能是因为strlen
一直试图找到null终止符,偶尔会在arr
之后的某个地方找到它。
Note that this code can even segfault, if null terminator will not be found "fast enough". 请注意,如果找不到null终结符“足够快”,则此代码甚至可能会发生段错误。
You can use tools like valgrind to detect such memory access violations. 您可以使用valgrind之类的工具来检测此类内存访问冲突。
In C
, a "string" has a NUL
character at the end. 在C
,“string”在末尾有一个NUL
字符。 A char[]
without NUL
is just a char[]
not a "string". 一char[]
没有NUL
仅仅是一个char[]
不是“字符串”。
Arrays in C
don't have their length stored anywhere, so strlen()
goes as long as NUL
hasn't been found. C
数组没有存储它们的长度,所以只要找不到NUL
, strlen()
就会一直存在。 You were probably lucky to have NUL
right few memory cells after array ended. 在阵列结束后,你可能很幸运NUL
几个存储单元。
Whenever you initialize string, the compiler adds nul
operator \\0
automatically for you. 每当初始化字符串时,编译器会自动为您添加nul
运算符\\0
。 For example,like what you are trying to do in your code is just making the char array, instead of doing this you can use, " "
and compiler will automatically add the \\0
for you same case when you ask input for string from users. 例如,就像你在代码中尝试做的那样只是制作char数组,而不是这样你可以使用" "
,当你向用户请求输入字符串时,编译器会自动为你添加\\0
。 But certainly there are cases when you need to add the nul
operator by yourself, example, when you are trying to break the character string word by word and try to save them in array of pointers , syntax : char *str[20]
then you have to have add \\0
at the end. 但肯定有些情况下你需要自己添加nul
运算符,例如,当你试图逐字逐句地破坏字符串并尝试将它们保存在指针数组中时,语法: char *str[20]
然后你必须在最后添加\\0
。 And If you are not happy with strlen()
function, you can code your own like this : 如果您对strlen()
函数不满意,可以像这样编写自己的代码:
size_t count = 0;
while (str != '\0'){ //str is the string name
count++;
}
Thank you! 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.