Reputation: 2045
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
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