简体   繁体   中英

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?

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);
}

You know that your function "stringLength" will never mutate/change the contents of the string right so make that function so

int somefunc(const char* ptr)
{
    const char* base=ptr;
    while(*(ptr++));
    return (ptr-base);
}

int main()
{
    printf("%d",somefunc("HELLO"));
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM