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
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
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);
}
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;
}
There is difference between ' quote and " quote in C. For strings " is used.
Change
int LengthofWord = strlen('word');
^ ^
| |
-----------Replace these single quotes with double quotes("")
to
int LengthofWord = strlen("word");
strlen returns size_t type. Declare it as size_t type instead of int. Also change the format specifier in the printf to %zu
printf("%d", LengthofWord);
Your final code should look like
int main(void)
{
size_t LengthofWord = strlen('word');
printf("%zu", LengthofWord);
return 0;
}