2012-11-06 129 views
2

我覺得這在指針基於Cint(* f [])();和int f []();

int f[](); /* this one is illegal */ 

和:

int (* f [])(); /* this one legal. */ 

我真的想知道什麼是第二個的使用。

謝謝。

+2

這個同樣的問題,今天問看看這個鏈接回答http://c-faq.com/decl/ spiral.anderson.html –

+2

非明顯聲明的有用網站:http://cdecl.org/ – hmjd

+2

你不能聲明一個函數數組(因爲函數佔用的內存是未知的)。你只能聲明一個指向數組的指針。 – nhahtdh

回答

2

第二個例子是相當有效的,如果你使用的初始化塊。對於example

#include <stdio.h> 
int x = 0; 
int a() { return x++ + 1; } 
int b() { return x++ + 2; } 
int c() { return x++ + 3; } 

int main() 
{ 
    int (* abc[])() = {&a, &b, &c}; 
    int i = 0, 
     l = sizeof(abc)/sizeof(abc[0]); 
    for (; i < l; i++) { 
    printf("Give me a %d for %d!\n", (*abc[i])(), i); 
    } 
    return 0; 
} 
+0

謝謝〜只是指出我很困惑。^_ ^ – lushl9301

1

我不確定第二個例子是合法的,因爲函數數組的大小是未知的,但它應該是一個函數指針數組,這裏是一個可能的用法示例if大小將是已知的:

int a() 
{ 
    return 0; 
} 

int main(int argc ,char** argv) 
{ 
    int (* f [1])(); 
    f[0] = a; 
} 
1

int f[](); //這是非法的,因爲你不能創建函數的數組。這是非法的C

但第二個是法律

int (* f [])();它說,f是函數指針返回int和採取的參數

未指定數量的數組
+0

我認爲下標具有更高的優先權嗎? – lushl9301

+0

不,'[]''()''''' - >'具有相同的優先級和相關性是左邊的 – Omkant

+0

您需要閱讀K&R的第5.12節 – Omkant

1
int f[](); /* this one is illegal */ 

這是試圖聲明函數數組,這是不可能的。

int (* f [])(); /* this one NOT legal, despite what the OP's post says. */ 

這是試圖聲明的功能的陣列指針,這是完全合法的(和理智)如果指定數組的大小,如:

int (* f [42])(); /* this one legal. */ 

編輯:int (* f [])()可以使用作爲函數參數類型,因爲對於函數參數類型,數組到指針的轉換立即發生,這意味着我們不會「T永遠需要指定一個(可能是多維)陣列的最裏面的陣列的尺寸:

void some_func(int (* f [])()); /* This is also legal. */