简体   繁体   English

为什么在 C 中 strlen() 可以获取字符串的长度而 sizeof 不能?

[英]Why strlen() can get the length of string and sizeof cannot in C?

I want to calculate the length of a string in C in VS Ccode, but when I use sizeof function, the time of compiling didn't stop and get any result;我想在VS Ccode中计算C中字符串的长度,但是当我使用sizeof函数时,编译的时间并没有停止并得到任何结果; on the other hand, I can get the length by strlen function: why?另一方面,我可以通过 strlen 函数获取长度:为什么?

#include <stdio.h>
#include <string.h>  
int main(int argc, char **argv)
{ 
    char greeting[] = "hello";

    int len = strlen(greeting);
    //int len = sizeof(greeting);       
    printf("length is:%d",len);
    return 0;
}

I know the difference between them: strlen() is used to get the length of an array of chars/string, while sizeof() is used to get the actual size of any type of data in bytes.我知道它们之间的区别: strlen()用于获取字符/字符串数组的长度,而sizeof()用于获取任何类型数据的实际大小(以字节为单位)。 However, I don't know why there is no answer when I run sizeof.但是,我不知道为什么我运行sizeof时没有答案。

You've invoked undefined behaviour: you're printing a value of type size_t with the format for an int .您调用了未定义的行为:您正在使用int格式打印size_t类型的值。 This is not guaranteed to work.这不能保证有效。 Cast the value:投射价值:

printf("length is: %d\n, (int)sizeof(greeting));

The result will be one larger than the result from strlen() because strlen() does not count the terminating null byte and sizeof() does.结果将比strlen()的结果strlen()因为strlen()不计算终止空字节而sizeof()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM