简体   繁体   English

将多个字符串存储在C的char数组中

[英]Store multiple strings in a char array in C

Today I saw a usage of char in C as followed: 今天我看到在C中使用char的方式如下:

    const char temp[] = "GET / HTTP/1.0\r\n"
                        "Host:www.google.com\r\n"
                        "\r\n";

At first, I thought there would be a compile error, but actually it passed the compilation! 起初,我以为会有编译错误,但实际上它通过了编译!
So can someone please tell me why it can work? 那么有人可以告诉我为什么它可以工作吗?
I am a fresh man learning C programming. 我是学习C编程的新生。
Thanks so much! 非常感谢!

If to place the missed semicolon at the end then this statement 如果将遗漏的分号放在最后,则此语句

const char temp[] = "GET / HTTP/1.0\r\n"
                    "Host:www.google.com\r\n"
                    "\r\n";

is equivalent to 相当于

const char temp[] = "GET / HTTP/1.0\r\nHost:www.google.com\r\n\r\n";

According to the C Standard in the section where translation phases are described there is written 根据描述翻译阶段的章节中的C标准编写

6. Adjacent string literal tokens are concatenated 6.相邻字符串文字标记被串联

Sometines it is convinient to split a long string literal that does not fit a line into several shorter adjacent literals. 对于某些例程,将不适合行的长字符串文字拆分为几个较短的相邻文字很方便。

const char str[] = "stringstringstring";

const char str[] = "string" "string" "string";

const char str[] = "string"
              "string"
              "string";

#define NAME "string"
const char str[] = "string" NAME "string";

Will all have the same result. 都会有相同的结果。 C concatenates adjacent strings. C连接相邻的字符串。

C has string literal concatenation , meaning that adjacent string literals are concatenated at compile time; C具有字符串文字串联 ,这意味着在编译时将相邻的字符串文字串联在一起; this allows long strings to be split over multiple lines, and also allows string literals resulting from C preprocessor defines and macros to be appended to strings at compile time. 这允许将长字符串拆分为多行,还允许将C预处理程序定义产生的字符串文字和宏在编译时附加到字符串。

For instance: 例如:

printf(__FILE__ ": %d: Hello "
       "world\n", __LINE__);

will expand to 将扩展到

printf("helloworld.c" ": %d: Hello "
       "world\n", 10);

which is syntactically equivalent to 在语法上等同于

printf("helloworld.c: %d: Hello world\n", 10);

It's a single string consisting of multiple concatenated string literals. 它是由多个串联字符串文字组成的单个字符串。 The C language allows string literals that appear next to each other without any operator in between to be concatenated to form a single string. C语言允许将彼此相邻出现的字符串文字串联在一起,而不必在其之间插入任何运算符以形成单个字符串。 This is useful for string constants that span multiple lines of source, as you've seen. 如您所见,这对于跨越多行源代码的字符串常量很有用。 It's also useful when a preprocessor macro defines a string literal, you can write something like 当预处理器宏定义字符串文字时,这也很有用,您可以编写如下内容

#define BALANCE_FMT "%5.2f"
printf("Your balance is: " BALANCE_FMT "\n", balance);

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

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