Search code examples
cstringcharacter-arrays

How do I pass an anonymous string literal to a function?


Since a string literal can be initialized like

char myString [] = "somestring";

it seems logical to be able to use a function like

int stringLength ( char * str )
{
   char * c2 = str;
   while (*c2++);
   return (c2-str);
}

and call it like

printf("%d",stringLength("somestring"));

However, I get an error when I do that.

Is there some way I can "cast" "something" into something proper to input into the function, or do I always have use an extra line like

char str [] = "somestring";
printf("%d",stringLength(str));    

or is there something else I should be doing altogether?


Solution

  • char myString [] = "somestring";
    

    creates an array of characters that are modifiable.

    When you use

    printf("%d",stringLength("somestring"));
    

    it is analogous to:

    char const* temp = "somestring";
    printf("%d",stringLength(temp));
    

    That's why the compiler does not like it.

    You can change the function to use a char const* as argument to be able to use that.

    int stringLength ( char const* str )
    {
       char const* c2 = str;
       while (*c2++);
       return (c2-str);
    }