围绕字符串字面大括号中的字符数组声明中无效? (例如个char [] = {"的Hello World"}) [英] Braces around string literal in char array declaration valid? (e.g. char s[] = {"Hello World"})

查看:172
本文介绍了围绕字符串字面大括号中的字符数组声明中无效? (例如个char [] = {"的Hello World"})的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无意间我发现,行个char [] = {Hello World的}; 正确编译并似乎一样对待个char [] =Hello World的; 。已经不是第一次( {的Hello World} )包含一个元素就是字符数组,这样的声明对于s应该读一个数组的char * S [] ?事实上,如果我将其更改为的char * S [] = {Hello World的}; 编译器接受它为好,如预期

By accident I found that the line char s[] = {"Hello World"}; is properly compiled and seems to be treated the same as char s[] = "Hello World";. Isn't the first ({"Hello World"}) an array containing one element that is an array of char, so the declaration for s should read char *s[]? In fact if I change it to char *s[] = {"Hello World"}; the compiler accepts it as well, as expected.

寻找答案,只有我发现这个地方里面提到这是<一个href=\"http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/aryin.htm\">this 之一,但没有理由的标准。

Searching for an answer, the only place I found which mentioned this is this one but there is no citing of the standard.

所以我的问题是,为什么行个char [] = {Hello World的}; 编译虽然左侧的类型为字符键,右侧的数组类型的字符数组的数组

So my question is, why the line char s[] = {"Hello World"}; is compiled although the left side is of type array of char and the right side is of type array of array of char?

以下是一个工作程序:

#include<stdio.h>
int main() {
    char s[] = {"Hello World"};
    printf("%s", s); // Same output if line above is char s[] = "Hello World";
    return 0;
}

感谢任何澄清。

P.S。我的编译器是gcc-4.3.4。

P.S. My compiler is gcc-4.3.4.

推荐答案

这是允许的,因为标准是这样说的:C99部分6.7.8,§14:

It's allowed because the standard says so: C99 section 6.7.8, §14:

字符类型的数组,可以用文字串进行初始化文字,任选
  大括号括起来。字符串字面量连续的字符(包括
  终止空字符,如果有空间,或者如果数组是未知大小的)初始化
  的数组的元素

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

这意味着,无论

char s[] = { "Hello World" };

char s[] = "Hello World";

只不过是语法糖多为

are nothing more than syntactic sugar for

char s[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', 0 };

在一个相关的说明(同款,§11),C也允许标量初始化括号像

On a related note (same section, §11), C also allows braces around scalar initializers like

int foo = { 42 };

这恰巧与语法复合文字非常适合

which, incidentally, fits nicely with the syntax for compound literals

(int){ 42 }

这篇关于围绕字符串字面大括号中的字符数组声明中无效? (例如个char [] = {&QUOT;的Hello World&QUOT;})的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆