How to create a string literal as a function argument using string concatenation in c

I need to pass a string literal to a function

myfunction("arg1" DEF_CHAR "arg1");

now part of this constructed string literal should be a return function

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

Is there a way to do this on a single line?

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

NOTE: C only please.

My goal is not to initialize a new char array for this = /

+3
source share
5 answers

You cannot create a string literal at runtime, but you can create a string, for example:

char param[BIG_ENOUGH];

strcpy(param, "arg1");
strcat(param, createString());
strcat(param, "arg2");
myfunction(param);
+4
source
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);
+2
source

C , , , . createString() , , . , , , - :

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

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

However, there are some problems with memory management and thread safety with this approach.

+2
source

To do this, you need to create an array of characters; only compilers are only concatenated by string literals.

+1
source

Nope. It is not possible to do this in pure C without allocating a new buffer to concatenate strings.

0
source

Source: https://habr.com/ru/post/1740523/


All Articles