strlen() in crashing .exe

329 views Asked by At
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

3

There are 3 answers

0
haccks On

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;
}
8
alk 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;
}
4
David Heffernan On

You have these problems with your code:

  • This is not valid: 'word'. The ' symbol is used for single characters, for instance 'a'. You meant to write "word".
  • The type of LengthofWord should be size_t rather than int since that is what strlen returns.
  • You used the wrong format string for 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.
  • Your main signature is incorrect – it should be 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);
}