Reed Debaets
Reed Debaets

Reputation: 522

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 =/

Upvotes: 3

Views: 989

Answers (5)

Peter Ruderman
Peter Ruderman

Reputation: 12485

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.

Upvotes: 2

N 1.1
N 1.1

Reputation: 12534

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

Upvotes: 2

Nick Meyer
Nick Meyer

Reputation: 40282

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

Upvotes: 0

qrdl
qrdl

Reputation: 34968

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

Upvotes: 4

jemfinch
jemfinch

Reputation: 2889

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

Upvotes: 1

Related Questions