C语言 为什么函数 strlen() 为两个 char 数组的相同长度返回不同的值?


#include <stdio.h>
#include<string.h>
int main() {

char a[50],b[50];// same sized arrays
for(int j =0;j<50;j++){
b[j]='b';a[j]='a';// initializing with the same number of elements
}
printf("the size of a is %ld,",strlen(a));
printf("the size of B is %ld",strlen(b));
return 0;
}

输出为

A 的大小为 50, B 的大小为 54

但我期望的是a 的大小是 50 B 的大小为 50

这里有什么问题?

这里有什么问题?

问题是你没有终止你的字符串。

C 要求字符串以 null 结尾:

C 字符串的长度是通过搜索(第一个(NUL 字节找到的。这可能很慢,因为它相对于字符串长度需要 O(n((线性时间(。这也意味着字符串不能包含 NUL 字符(内存中有一个 NULL,但它在最后一个字符之后,而不是"在"字符串中(。

#include <stdio.h>
#include<string.h>
int main() {
char a[50],b[50];// same sized arrays
for(int j =0;j<50;j++){
b[j]='b';a[j]='a';// initializing with the same number of elements
}
// Terminate strings
a[49] = b[49] = 0;
printf("the size of a is %ld,",strlen(a));
printf("the size of B is %ld",strlen(b));
return 0;
}

给出正确的结果。

最新更新