2017-09-24 96 views
4

我有一個數組,看起來像這樣:void *的函數指針數組轉換

void* functions[]; // pointer to functions, each function returns an int and has int parameters A and B 

我想丟在下面這段:

int (*F)(int a, int b) = ((CAST HERE) functions)[0]; 
int result = F(a, b); 

我已經嘗試過「(INT( *)(int,int))「作爲轉換,但編譯器抱怨我試圖使用函數指針作爲數組。

+0

編譯器是正確的。檢查你的括號。 (0); –

+1

可以嘗試:'int(* F)(int,int)=(int(*)(int,int))functions [0];' – 4386427

+1

使用typedef ... –

回答

0

function是指向void類型數據的指針數組。你想把它轉換爲指針,以int (*)(int, int)類型的指針,這將是int (**)(int, int),所以下面的工作:

int (*F)(int, int) = ((int (**)(int, int)) functions)[0]; 

正如指出的@M.M,上面會導致未定義行爲。你可能想閱讀this文章和this以瞭解更多。


理想情況下,你會做這樣的事情:

// Array of 2 pointers to functions that return int and takes 2 ints 
int (*functions[2])(int, int) = {&foo, &bar}; 

// a pointer to function 
int (*F)(int, int) = functions[0]; 
int r = F(3, 4); 
+1

這會導致未定義的行爲 –

+0

我測試了這個,它似乎適用於我的應用程序,謝謝! – Jas

+0

@Jas - 未定義的行爲並不意味着「沒有工作」。它可能「似乎長時間工作」,直到在移動到新的平臺時沒有明顯的原因。那時你已經忘了這篇文章,不得不加班加點弄清楚你搞砸了。 – StoryTeller

4

這將有助於使用typedef爲函數類型:

typedef int F_type(int, int); 

然後,你可以寫:

F_type *F = (F_type *)(functions[0]); 

這將是不確定的行爲(嚴格別名衝突),試圖投functions到使用索引操作符之前的其他東西。

請注意,標準C不支持將void *轉換爲函數指針。如果可能的話,使數組是擺在首位的函數指針:

F_type *functions[] = { &func1, &func2 }; 

NB。有些人更喜歡使用typedef作爲函數指針類型,而不是函數類型。我認爲它會提供更多可讀代碼來避免指針typedef,但是我提到了這一點,以便您瞭解其他建議。

+0

好的答案,但我擔心OP不想要'typedef'。 – gsamaras

+0

@gsamaras當然。我低估了你的答案,因爲它會導致未定義的行爲。另外你聲稱OP的基礎是什麼不想要typedef? –

+0

真的嗎?嗯,我不確定爲什麼,你能解釋一下嗎?我可能是錯的,因爲nm告訴OP關於typedef,然後OP回答我不能這樣做,但他回答了mm ..對不起! – gsamaras

2

(int (**)(int, int))鑄造似乎現在做的伎倆,但它調用未定義行爲

轉換void*起作用指針不是標準C.

注意,混疊void*到不同類型的;嚴格的鋸齒違規。更多詳情,請參閱What is the effect of casting a function pointer void?

請考慮從頭開始使用函數指針數組。

+2

別名和轉換是不同的事情。別名不兼容的類型違反嚴格的別名規則,它不會調用轉換。例如,比較'double d [2] = {5.0,6.0}; int x = d [0];'(轉換)與'int y =((int *)&d)[0];'(混疊) –

相關問題