gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:10:58 26 4
gpt4 key购买 nike

我教授的期末考试主要由非常棘手的语法组成。例如,他的一些问题就像“使用指针 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,8},{11,12}};

类似的语法会起作用。

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

最佳答案

编译器,在大多数情况下,会将上面的初始化解析为

int a[2][2][2] = { { {5,6}, {7,8} }, 
{ {9,10}, {11,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

int y[4][3] = {
{ 1, 3, 5 },
{ 2, 4, 6 },
{ 3, 5, 7 },
};

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

int y[4][3] = {
1, 3, 5, 2, 4, 6, 3, 5, 7
};

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].

关于c - 这些三维数组在 C 中合法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45359443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com