warning: it says to change %d for %I64d
char string[DIM]="hello";
printf("%d",strlen(string));
As @AndreasWenzel answered "%zu" is the most most correct. But you wrote:
it outputs this warning when I put %zd warning: unknown conversion type character 'z' in format
if your implementation does not support "%z..." formats you need to convert the result of strlen to the largest possible unsigned integer.
printf( "%llu", (unsigned long long)strlen(string) );
But if your implementation does not support "%llu"
printf( "%lu", (unsigned long)strlen(string) );
And the last resort:
printf( "%u", (unsigned)strlen(string) );
printf( "%lu", (unsigned long)strlen(string) ); is the typical hack for MS (or other old) code and to maintain portability and future growth.(int) to match OP question about compatibility with "%d" ?The %d printf format specifier expects an int. However, the return value of strlen is of type size_t.
The correct printf format specifier for size_t is %zu.
This line should work:
printf( "%zu", strlen(string) );
float and double when using printf (in contrast to scanf) is that the float parameter gets promoted to a double, because printf is a variadic function. However, int does not get promoted to size_t.strlen doesn't return int. But your printf formats and their arguments must match. So just say
printf("%d", (int)strlen(string));
As long as your string is never longer than 32767 characters, you'll be fine.
The preferred solution is
printf("%zu", strlen(string));
but it sounds like your antique compiler doesn't support %zu. (You have my sympathies: I had a compiler at work for a long time that had the same problem.)
If you're worried about strings longer than 32767 characters, see the other answers, or this question: How can one print a size_t variable portably using the printf family?
strlen(int) is considerably easier to type than (unsigned). (And for reasonable-length strings, it won't make a difference.)
strlen()returnssize_t, use%zuas format specifier."%zu"wasn't supported, think I had to use"%Iu".. ?printf, argument types must match their format specifiers, and doing so is your responsibility; the compiler will generally not insert any automatic conversions to match them up for you. At best the compiler will warn you about mismatches. (Modern compilers do try to warn you, and are recommended for this reason.)