简体   繁体   English

如何通过c中的字符串连接创建一个字符串文字作为函数参数

[英]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. 注意:请仅限C。

My goal is to avoid initializing a new char array for this =/ 我的目标是避免为此初始化一个新的char数组= /

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. C不支持动态字符串,所以你尝试的是不可能的。 The return value from your createString() function is a variable, not a literal, so you can't concatenate it with other literals. createString()函数的返回值是一个变量,而不是文字,因此您无法将其与其他文字连接起来。 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. 如果没有分配新的缓冲区来连接字符串,就无法在纯C中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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