这些三维数组在C中合法吗?

前端之家收集整理的这篇文章主要介绍了这些三维数组在C中合法吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我教授的期末考试主要包括非常棘手的语法.例如,他的一些问题就像是“使用指针1打印字母k而不使用括号.幸运的是它是打开的书.

所以有一个问题是:

int a[2][2][2] = {{5,6},{7,8},{9,10},{11,12}};

写一个打印出“7910”的printf语句.使用指针而不使用方括号.

起初,我认为这是一个错字或非法阵列.我以为数组应该从左边的第三个数组停止.

我写:

printf("%d%d%d\n",*(*(a+1)+1)),*(*(a+2)),*(*(a+2)));

我把它放了,因为如果阵列是

int a[2][2] = {{7,12}};

类似的语法会起作用.

这是一个错字吗?如果没有,那么正确的语法是什么?

解决方法

在大多数情况下,编译器会将上面的初始化解析为
int a[2][2][2] = { { {5,8} },{ {9,12} }
                 };

如果您将其写为,这也将起作用

int a[2][2][2] = {5,6,7,8,9,10,11,12};

但这确实不是一个好习惯.

C标准说的
§6.7.9(P17):

When no designations are present,subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order,structure members in declaration order,and the first named member of a union149). […]

P26

EXAMPLE 3 The declaration

06002

is a definition with a fully bracketed initialization: 1,3,and 5 initialize the first row of y (the array object y[0]),namely y[0][0],y[0][1],and y[0][2]. Likewise the next two lines initialize y[1] and y[2]. The initializer ends early,so y[3] is initialized with zeros. Precisely the same effect could have been achieved by

06003

The initializer for y[0] does not begin with a left brace,so three items from the list are used. Likewise the next three are taken successively for y[1] and y[2].

原文链接:https://www.f2er.com/c/119121.html

猜你在找的C&C++相关文章