简体   繁体   中英

how to create a string literal as a function argument via string concatenation in c

I need to pass a string literal to a function

myfunction("arg1" DEF_CHAR "arg1");

now part of that constructed string literal needs to be a function return

stmp = createString();
myfunction("arg1" stmp "arg2"); //oh that doesn't work either

is there any way to do this in one line?

myfunction("arg1" createString() "arg2"); //what instead?

NOTE: C only please.

My goal is to avoid initializing a new char array for this =/

You cannot build string literal at runtime, but you can create the string, like this:

char param[BIG_ENOUGH];

strcpy(param, "arg1");
strcat(param, createString());
strcat(param, "arg2");
myfunction(param);
char buffer[1024] = {0};
//initialize buffer with 0 
//tweak length according to your needs

strcat(buffer, "arg1");
strcat(buffer, createString()); //string should be null ternimated
strcat(buffer, "arg2");

myfunction(buffer);

C does not support dynamic strings, so what you're attempting is impossible. The return value from your createString() function is a variable, not a literal, so you can't concatenate it with other literals. That being said, if it's really important to you to have this on one line, you can create a helper function to facilitate this, something like the following:

char * my_formatter( const char * format, ... )
{
...
}

myfunction(my_formatter("arg1%sarg2", createString()));

There are some memory management and thread saftey issues with this approach, however.

You need to make a character array for this; only string literals are concatenated by the compiler.

Nope. No way to do this in pure C without allocating a new buffer to concatenate the strings.

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