简体   繁体   中英

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; on the other hand, I can get the length by strlen function: why?

#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. However, I don't know why there is no answer when I run sizeof.

You've invoked undefined behaviour: you're printing a value of type size_t with the format for an int . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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