int main()
{
int LengthofWord = strlen('word');
printf("%s", LengthofWord);
}
For some reason this code is crashing. I want to retrieve the length of a string ( in this case string) to use later on. Why is this code crashing?
Thanks
On
It should be
... = strlen("word");
In C string literals are put into double quotation marks.
Also strlen() returns size_t not int. So the full line shall look like this:
size_t LengthofWord = strlen("word");
Finally to print out a size_t use the conversion specifier "zu":
printf("%zu", LengthofWord);
A "%s" expects a 0-terminated array of char, a "string".
Last not least, start the program using
int main(void)
{
...
and finish it by returing an int
...
return 0;
}
On
You have these problems with your code:
'word'. The ' symbol is used for single characters, for instance 'a'. You meant to write "word".LengthofWord should be size_t rather than int since that is what strlen returns.printf. You used %s which is appropriate for a string. For an integral value, you should use %zu. Although, do beware that some runtimes will not understand %zu.int main(void)So your complete program should be:
#include <stdio.h>
#include <string.h>
int main(void)
{
size_t LengthofWord = strlen("word");
printf("%zu", LengthofWord);
}
There is difference between
'quote and"quote in C. For strings"is used.Change
to
strlenreturnssize_ttype. Declare it assize_ttype instead ofint. Also change the format specifier in theprintfto%zuYour final code should look like