微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

这些三维数组在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.jb51.cc/c/119121.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐