4daJKong
4daJKong

Reputation: 2045

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.

Upvotes: 0

Views: 1063

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753515

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.

Upvotes: 2

Related Questions