Ran*_*vas 3 c null sizeof strlen
我知道字符串的结尾由空字符表示,但我无法理解以下代码的输出.
#include <stdio.h>
#include <string.h>
int
main(void)
{
char s[] = "Hello\0Hi";
printf("%d %d", strlen(s), sizeof(s));
}
Run Code Online (Sandbox Code Playgroud)
输出:5 9
如果strlen()在o的末尾检测到字符串的结尾,那为什么sizeof()不做同样的事情呢?即使它没有做同样的事情,也不是'\ 0' 一个空字符(即只有一个字符),所以答案不应该是8吗?
Iha*_*imi 17
该sizeof运营商不给你一个字符串的长度,而是它的操作数的类型的大小.因为在您的代码中操作数是一个数组,sizeof所以给出了包含两个null字符的数组大小.
如果是这样的话
const char *string = "This is a large text\0This is another string";
printf("%zu %zu\n", strlen(string), sizeof(string));
Run Code Online (Sandbox Code Playgroud)
结果将是非常不同的,因为string是一个指针,而不是一个数组.
注意:使用"%zu"说明符size_t是什么strlen()返回,并且是给定的值的类型sizeof.
strlen()不关心字符串的实际大小.它查找空字节并在看到第一个空字节时停止.
但是sizeof()运营商知道总的大小.它不关心你在字符串文字中的字节数.您可能还有字符串中的所有空字节,并且sizeof()仍然会给出正确的数组大小(0在这种情况下strlen()会重新运行).
它们没有可比性; 他们做不同的事情.
如果 strlen() 在 o 的末尾检测到字符串的结尾,那么为什么 sizeof() 不做同样的事情呢?
strlen仅适用于字符串(字符数组),而sizeof适用于每种数据类型。sizeof计算任何给定数据类型的确切内存空间;而strlen提供字符串的长度(不包括 NULL 终止符\0)。所以在正常情况下,这对于典型的字符数组是正确的s:
char s[] = "Hello";
strlen( s ) + 1 = sizeof( s ); // +1 for the \0
Run Code Online (Sandbox Code Playgroud)
在您的情况下,情况有所不同,因为您在字符数组中间有一个 NULL 终止符s:
char s[] = "Hello\0Hi";
Run Code Online (Sandbox Code Playgroud)
在这里,strlen将检测第一个\0并给出长度为 5。sizeof然而,将计算足以容纳字符数组的空格总数,包括两个\0,这就是为什么它给出 9 作为第二个输出。
strlen()计算字符串的长度。这是通过返回该字符之前(且不包括该'\0'字符)的字符数来完成的。(请参阅下面的手册页。)
sizeof()返回给定变量(或数据类型)的字节数。请注意,您的示例"Hello\0Hi"有 9 个字符。但你似乎不明白你的问题中的字符9来自哪里。让我先解释一下给定的字符串。您的示例字符串是:
"Hello\0Hi"
Run Code Online (Sandbox Code Playgroud)
这可以写成以下数组:
['H', 'e', 'l', 'l', 'o', '\0', 'H', 'i', '\0']
Run Code Online (Sandbox Code Playgroud)
请注意最后一个'\0'字符。当使用字符串引号时,编译器以一个字符结束字符串'\0'。这意味着""也是['\0']并且因此具有 1 个元素。
请注意,它sizeof()不会返回数组中的元素数量。它返回字节数。是 1 个字节,因此返回元素的数量。但是,如果您使用任何其他数据类型,例如如果您调用它将返回 16。因为是 4 个字节,并且该数组有 4 个元素。charsizeof()sizeof()[1, 2, 3, 4]int
请注意,传递数组作为参数只会传递指针。如果您传递s给另一个函数并调用sizeof()它将返回指针的大小,这与sizeof(void *). 这是独立于数组的固定长度。
Run Code Online (Sandbox Code Playgroud)STRLEN(3) BSD Library Functions Manual STRLEN(3) NAME strlen, strnlen -- find length of string LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <string.h> size_t strlen(const char *s); size_t strnlen(const char *s, size_t maxlen); DESCRIPTION The strlen() function computes the length of the string s. The strnlen() function attempts to compute the length of s, but never scans beyond the first maxlen bytes of s. RETURN VALUES The strlen() function returns the number of characters that precede the terminating NUL character. The strnlen() function returns either the same result as strlen() or maxlen, whichever is smaller. SEE ALSO string(3), wcslen(3), wcswidth(3) STANDARDS The strlen() function conforms to ISO/IEC 9899:1990 (``ISO C90''). The strnlen() function conforms to IEEE Std 1003.1-2008 (``POSIX.1''). BSD February 28, 2009 BSD