字符串文字可以与 char* 连接吗?

Gal*_*axy 1 c string-literals char-pointer

我知道在 C 中相邻的字符串文字是连接在一起的。我想知道,相邻的字符串文字是否与 char*s 连接?

我问这个问题的原因是因为我想将两个字符串的串联传递给perror(),并且其中一个字符串事先未知,所以我必须使用char*.

perror("error opening " "file.txt");  // string literals are concatenated

char* filename = "file.txt";  // or some other file
perror("error opening " filename);    // will this work?
Run Code Online (Sandbox Code Playgroud)

Eri*_*hil 5

不会。字符串文字的串联是在翻译(编译)期间执行的。您请求的操作必须在程序执行时在程序内完成。没有规定可以自动执行此操作;您必须编写代码来为结果字符串分配空间并执行连接。