2012-11-14 43 views
1

im在ANSI C中編寫程序,並且有一個函數,其中im傳遞指向信號量指針的指針struct sembuf semb[5]Ansi C - 函數期望指針指向數組

現在功能的頭部看起來像:

void setOperations(struct sembuf * op[5], int nr, int oper) 

但即時得到警告:

safe.c:20: note: expected ‘struct sembuf **’ but argument is of type ‘struct sembuf (*)[5]’ 

如何解決這個問題?

編輯
通話:

setOperations(&semb, prawa, -1); 
+2

你的函數調用是什麼樣的? – dst2

+0

你需要兩次指示燈的指示,而你沒有。顯示實際通話的代碼 – SomeWittyUsername

+0

啊,我忘了:setOperations(&semb,prawa,-1); – marxin

回答

6

這是函數應該如何申報,如果你想要一個指針傳遞給數組,而不是指針數組:

void setOperations(struct sembuf (*op)[5], int nr, int oper); 
3

您當前的聲明(struct sembuf * op[5])指5個指針數組以struct sembuf

無論如何,數組都是作爲指針傳遞的,所以在頭文件中你需要:struct sembuf op[5]。 無論如何將傳遞一個指向數組的指針。沒有數組將被複制。 聲明此參數的替代方法是struct sembuf *op,這是指向struct sembuf的指針。

+0

嚴。那麼,如何爲5個結構數組的指針聲明頭? – marxin

+0

指向5個結構數組的指針與C語言中指向該數組第一個元素的指針相同。沒有額外的信息隱藏在C數組中,而不是第一個元素的地址,所以不需要顯式指針。 –

+0

這不是我即時要求的:P我明白了,我可以傳遞一個指向第一個元素的指針,並且會很好。我現在也知道如何傳遞指向數組的指針(Vaughn Cato響應)。 Thx無論如何 – marxin

0

你也許在這個複雜...

如果您想要傳遞一個結構數組,它實際上和傳遞任何數組沒有什麼不同。一旦你的陣列,獲得的地址很簡單,讓我給你一個簡單的例子:

比方說,你有這樣的結構:如果你想聲明它靜態地在你的main()可以

typedef struct s { 
    int a; 
    int b; 
} mys; 

更多信息:

int main(int argc, char *argv[]) 
{ 
    mys local[3]; 
    memset(local, 0, sizeof(mys)*3); // Now we have an array of structs, values are 
             // initialized to zero. 

    // as a sanity check let's print the address of our array: 
    printf("my array is at address: %#x\n", local); 

    changeit(local, 3); // now we'll pass the array to our function to change it 

現在我們可以有我們的函數,它接受陣列並更改值:

void changeit(mys remote[], int size) 
{ 
    int count; 
    printf("my remote array is at address: %#x\n", remote); //sanity check 
    for(count = 0; count < size; count++) { 
     remote[count].a = count; 
     remote[count].b = count + size; 
    } 
} 

一旦返回,我們可以從main()與其他一些環一樣打印值:

for(int count = 0; count < 3; count ++) 
    printf("struct[%d].a = %d\n struct[%d].b = %d\n", 
      count, local[count].a, count, local[count].b); 

而且我們會得到一些輸出,看起來像:

>> ./a.out 
    my array is at address: 0xbf913ac4 
    my remote array is at address: 0xbf913ac4 
    struct[0].a = 0 
    struct[0].b = 3 
    struct[1].a = 1 
    struct[1].b = 4 
    struct[2].a = 2 
    struct[2].b = 5 

所以你可以看到它是相同的數組(相同的地址),這就是你如何獲得結構數組到另一個函數。它清楚了嗎?

+0

我知道Mike。謝謝。 Vaughn Cato很好地回答了我的問題。我正在傳遞指針數組,而不是指向數組的指針。那是所有:)但thx;) – marxin

+0

@ user1040813 - 酷,很高興你得到它! – Mike

+0

@ user1040813 - 不知道爲什麼你需要傳遞一個指向數組的指針? – Mike