所以我正在学习C,我想问一下我的说法是否正确。
数组名称会转换为指针,但以下两种情况除外:使用 sizeof 或 & 运算符
数组名称是指向数组第一个元素的指针,例如
int array[10]; int* pointer = array; // int* pointer = &array[0]; is the same
这里有两个数组和一些表达式(用作左值表达式)。我感兴趣的是表达式返回类型是否正确?
int B[2][3];
3. &B[0] type is int (*)[3]
4. &B type is int (*)[2][3]
5. sizeof(B) here B type is int[2][3]
6. B+1 type is int (*)[3]
7. *(B+1) type is int[3] // 8. here th type int[3] and int* is not the same right?
8. *(B+1) + 2 type is int*
9. *(*B+1) type is int
10. &(*B+1) type is int (**)[3]
11. **B type is int
int c[3][2][5];
12. &c[0] type is int (*)[2][5]
13. *c type is int[2][5]
14. *(*c+1) type is int[5]
15. &*c type is int (*)[2][5]
16. &**c type is int (*)[5]
如果我错了,如果您能纠正,我将不胜感激。
最佳答案
第 1 点和第 2 点最好说一下,当表达式由数组名称组成时,表达式的值是指向数组第一个元素的指针(除了少数值得注意的情况)。
第 3-14 点均正确,但第 10 点格式错误。 *B + 1
不是左值,因此您无法获取它的地址。
第 15 点有点有趣。在 C11 标准中,第 6.5.3.2/3 节说:
The unary
&
operator yields the address of its operand. [...] If the operand is the result of a unary*
operator, neither that operator nor the&
operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.
乍一看,这似乎指定 &*c
的行为应与 c
相同,即具有类型 int[3][2][5 ]
。 (C99没有这个文本)。
另一方面,*
运算符的约束之一是:
The operand of the unary
*
operator shall have pointer type.
由于约束“仍然适用”,也许我们实际上应该得出结论:&*E
相当于衰减的 E
,而不是原始的 E
,当 E
具有数组类型时。此解释也符合指定数组指针转换的 6.3.2.1/3。如果 6.5.3.2/3 明确提到将值转换应用于表达式 &*E
的 E
,也许会更清楚。
关于C:理解多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35709699/