将指针转换为指向数组的指针

时间:2015-10-14 10:00:57

标签: c

以下是代码段。我想知道line no. 17类型转换在c?

中是否有效且正确
#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);
}

我在编译时遇到警告,而o / p不合适。

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);

根据我的理解,数组在函数参数中衰减为pointer to int。究竟是什么原因?

1 个答案:

答案 0 :(得分:3)

a是一个数组。因此,当您将其传递给intermediate()时,它会转换为指向其第一个元素的指针(又名&#34;数组衰减&#34;)。

所以,b位于:

void intermediate(twoInts b) {
    print(&b);
}

的类型为int*,而不是您所期望的int[2]。因此,&b类型为int**,而不是int (*)[2]函数所期望的print()。 因此,这些类型不匹配。

如果您将intermediate()更改为:

void intermediate(twoInts *b) {
    print(b);
}

然后你不需要传递&b的地址,它会按预期传递,并且类型会正确匹配。

相关问题