2014-01-16 33 views
3

如果我有struct example *efunction(&e)function(e)之間有什麼區別?結構示例* e:函數(&e)和函數(e)之間的區別

一個例子。

這是第一個代碼:

#include <stdio.h> 

struct example 
{ 
    int x; 
    int y; 
}; 

void function (struct example **); 

int main() 
{ 
    struct example *e; 

    function (&e); 

    return 0; 
} 

void function (struct example **e) 
{ 
    /* ... */ 
} 

這是第二個代碼:

#include <stdio.h> 

struct example 
{ 
    int x; 
    int y; 
}; 

void function (struct example *); 

int main() 
{ 
    struct example *e; 

    function (e); 

    return 0; 
} 

void function (struct example *e) 
{ 
    /* ... */ 
} 

是什麼這兩個代碼之間的區別? 謝謝!

回答

7

第一個您傳遞一個指向該結構的指針的地址。在你傳遞結構的地址。

在這兩種情況下function可以改變結構,你通過它:

(*e)->x = 10; // First, needs additional dereferencing *. 

e->x = 10; // Second. 

在第一個,你也可以給main()e不同的值,例如另一個結構的地址分配給它,或者將其設置爲NULL

*e = NULL; 

你居然忘了一個第三情況:

function(struct example e) { ... } 

這裏函數獲取你傳遞它的結構的副本。

+1

但在第二種情況下,我可以在函數中執行'e = malloc(2 * sizeof(struct example))'嗎? –

+1

@user你可以,但是你只能在函數中本地修改'e'。函數參數'e'按值傳遞。 –

+1

好吧,在第一個如果我做'* e = malloc(2 * sizeof(struct example))'我也在'main()'中更改它,對吧? –

2

第一個例子可以自己改變'e'(f.e. Malloc()它並返回它)。 這兩個例子都可以改變'e'的內容,如果它是混合的。

+1

_ @ Peter Miehle_。你的意思是說,在第一個代碼中,我可以在函數中使用malloc,比如'* e = malloc(2 * sizeof(struct example));'而在第二種情況下不是? –

1

the structure位於「雲」的某處。您正在處理指向它的指針,它們是簡單變量,包含the structure的地址。在第一個示例中,您可以更改the pointerthe structure。從第二個示例中,您只能更改the structure,但只能更改爲a pointer(本地副本)。

當在第二示例的e = malloc ...做,那麼the structure繼續存在於「雲」,但是在創建一個新的,其中,你丟失任何連接時function結束(=內存泄漏)。從main的角度來看,一切都保持不變。

在C++中,你可以改變你的第二個例子,像這樣void function (struct example *&e)具有與第一個相同的行爲,但是可以自動取消「指針指針」e(引用是某種自動解引用指針)。

相關問題