Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从K&;R c编程手册,第3.9节末尾_C - Fatal编程技术网

从K&;R c编程手册,第3.9节末尾

从K&;R c编程手册,第3.9节末尾,c,C,我对c中的字符串长度考虑了很多,字符串以空字符结尾,空字符是“\0”,它在文本中不可见,正如我们从c代码中看到的: #include <stdio.h> #include <string.h> int main(){ char s1[] = "ould"; printf("ould string length is %ld\n", strlen(s1)); char s2[] = {'o','u','l','

我对c中的字符串长度考虑了很多,字符串以空字符结尾,空字符是“\0”,它在文本中不可见,正如我们从c代码中看到的:

#include <stdio.h>
#include <string.h>
int main(){
    char s1[] = "ould";
    printf("ould string length is %ld\n", strlen(s1));
    char s2[] = {'o','u','l','d','\0'};
    printf("ould string length is %ld\n", strlen(s2));
    return 0;
}
#包括
#包括
int main(){
字符s1[]=“ould”;
printf(“ould字符串长度为%ld\n”,strlen(s1));
字符s2[]={'o','u','l','d','\0'};
printf(“ould字符串长度为%ld\n”,strlen(s2));
返回0;
}
这本书在第3.9节末尾说,s2是等效的,但数组大小是5,从运行结果来看,它是4,从我的理解和搜索来看,字符串以“\0”结尾,但“\0”将不包括在字符串长度中,但作者为什么说它是5? 任何人都可以分享这方面的想法或清晰性吗?

不要将
sizeof(x)
strlen(x)
混淆。
sizeof
运算符返回某些内容的内存占用空间:

char缓冲区[1024]=“测试”;
这里
sizeof(buffer)
1024
,而
strlen(buffer)
4
,但在另一种情况下:

char*buffer=“测试字符串”;

这里
sizeof(buffer)
8
(64位),而
strlen(buffer)
14
,字符串的长度是第一个空字符之前的字符数。包含字符o、u、l、d和空字符的字符串长度为4

数组的大小是数组中的字节数(或者在某些上下文中是数组中的元素数)。包含字符o、u、l、d和空字符的数组的大小为5

strlen(s2)
返回
s2
中字符串的长度


sizeof s2
计算为数组的大小
s2

strlen
不是数组大小。它是字符串的大小,最大为(不包括)
'\0'
。包含它的数组可能要大得多。包含字符串的字符数组必须至少比它所包含的字符串大1个字符,才能有空间容纳终止的空字符。字符串长度不包括此终止的空字符。因此,数组大小为5,字符串长度为4。字符串长度为4,字符数组大小为5。如果有空终止符的空间,可以使用字符数组来表示字符串。就这样。请参阅链接的副本。