简体   繁体   English

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

[英]Can a string literal be concatenated with a char*?

I know that in C adjacent string literals are concatenated. 我知道在C中,相邻的字符串文字是连接在一起的。 I want to know, are adjacent string literals concatenated with char*s? 我想知道,相邻的字符串文字是否与char * s连接在一起?

The reason I'm asking this question is because I want to pass a concatenation of two strings to perror() , and one of the strings is not known in advance so I have to use a char* . 我问这个问题的原因是因为我想将两个字符串的连接传递给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?

No. Concatenation of string literals is performed during translation (compilation). 否。字符串文字的串联是在翻译(编译)过程中执行的。 The operation you are requesting must be done within the program when it is executing. 执行程序时,必须在程序内完成您请求的操作。 There is no provision for doing it automatically; 没有自动执行此操作的规定; you must write code to allocate space for the resulting string and to perform the concatenation. 您必须编写代码为结果字符串分配空间并执行串联。

No. Adjacent string literals being concatenated is a capability of the compiler, which treats adjacent string literals as one string literal, in order to help coders write readable code (in case of a large string literal that would not fit on a line nicely). 否。串联的相邻字符串文字是编译器的功能,它将相邻的字符串文字视为一个字符串文字,以帮助编码人员编写可读代码(如果大字符串文字不能很好地放在一行上)。

C as a language does not have a concatenation operator, the closest you can get to it is a function ( strncat , strcat . strcpy , memcpy ). C作为语言不具有连接运算符,你可以得到它最接近的是一个函数( strncatstrcatstrcpymemcpy )。

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

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