以下是代码片段。我想知道在c语言中,
此外,当我将定义
据我理解,数组在函数参数中会退化为
第17行
的类型转换是否有效和正确?#include <stdio.h>
typedef int twoInts[2];
void print(twoInts *twoIntsPtr);
void intermediate (twoInts twoIntsAppearsByValue);
int main () {
twoInts a;
a[0] = 0;
a[1] = 1;
print(&a);
intermediate(a);
return 0;
}
void intermediate(twoInts b) {
print((int(*)[])b); // <<< line no. 17 <<<
}
void print(twoInts *c){
printf("%d\n%d\n", (*c)[0], (*c)[1]);
}
此外,当我将定义
intermediate
更改为void intermediate(twoInts b) {
print(&b);
}
编译时我收到以下警告,输出结果不正确。
1.c:17:11: warning: passing argument 1 of print from incompatible pointer type
print(&b);
^
1.c:5:6: note: expected int (*)[2] but argument is of type int **
void print(twoInts *twoIntsPtr);
据我理解,数组在函数参数中会退化为
指向int的指针
。这是什么原因?
void print(twoInts *twoIntsPtr);
和void print(int (*twoIntsPtr)[2]);
是相同的,换句话说,不要在typedef后面隐藏数组和指针。 - thisint *
指针,而无需使程序变得模糊不清。 - Lundinprint((twoInts *)&b);
应该可以。 - alk