[英]casting pointer to pointer to an array
以下是代碼段。 我想知道是否line no. 17
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
。 究竟是什么原因?
a
是一個數組。 因此,當您將其傳遞給intermediate()
,它會轉換為指向其第一個元素的指針(也稱為“數組衰減”)。
那么, b
in:
void intermediate(twoInts b) {
print(&b);
}
你可能會有類型int*
,而不是int[2]
。 因此, &b
的類型為int**
而不是int (*)[2]
,這是print()
函數所期望的。 因此,類型不匹配。
如果您將intermediate()
更改為:
void intermediate(twoInts *b) {
print(b);
}
然后你不需要傳遞&b
的地址,它將按預期方式,並且類型將正確匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.