2013-09-05 44 views
3

在C中,我試圖通過發送指向獨立函數的指針來爲結構分配內存。我知道需要malloc()來分配內存,但我對這個過程有點困惑。發送函數指針

如果我有一個函數:

void allocate(structure *ptr){ 
     ptr = malloc(sizeof(ptr)); //ptr assigned memory block address 
    } 

我分配的內存塊等於結構的大小,而只是發送給函數的原指針的副本。當函數將控制權返回給調用函數時,ptr會丟失,現在我們有內存泄漏。

基本上我想要做的是將一個結構類型的指針發送給一個函數併爲結構分配內存。


我知道這可能喜歡的東西來完成:

structure *allocate(structure *ptr) 

其中呼叫是值得的影響:

some_struct_ptr = allocate(some_struct_ptr); 

但如何可以做其他的方式?

+0

你能解釋爲什麼你不能簡單地返回一個指向分配的內存? – Ancurio

回答

1

pointers是數值(通常用一個字或註冊在您的機器中)。

始終初始化指針(可能爲NULL)是一種好習慣。

allocate這樣的函數需要一些指針並立即替換該指針正在丟失原始指針的值。

順便說一句,你可能有一個

typedef struct somestruct_st structure; 

,我寧願structure_t而不是structure作爲一個類型名稱。

所以基本上,你的函數的行爲就像

void allocate(structure *ptrold){ 
    /// ptrold is never used in this function 
    structure* ptr = malloc(sizeof(ptr)); 
} 

除非你做一些與當地ptr你的函數是leaking memory。你或許應該返回ptr,或者把它放到某個位置(可能是內存領域的一些結構或一些全局變量中)

的可能方式可能是通過你的指針的地址,這是一個指針的指針;

void allocate (structure **pptr) 
    { 
    structure *oldptr = *pptr; 
    /// etc... 
    } 

當然,你會打電話給在這種情況下allocate(&someptr)

我的建議是處理functional programming風格的指針:避免修改它們,只是新分配它們:所以我不喜歡realloc,我不喜歡傳遞指針的地址。

2

你可以這樣來做:

void allocate(structure **ptr) 
{ 
    // Allocate memory for a single structure and put that address into the location 
    // that ptr points to. ptr is assumed to be the address of the pointer given 
    // by the caller 

    *ptr = malloc(sizeof(structure)); 
} 

所以,當你想在一個參數返回一個值,你需要傳遞的是變量的地址,然後將值賦給什麼地址指向。因爲在這種情況下,變量是一個指針,所以你傳入一個指針的地址,換句話說,就是一個指向指針的指針。然後賦值*ptr =...表示「爲該地址指向的指針分配一個地址」。

然後調用它,你傳遞你想設置的指針的地址:

structure *my_ptr; 

// Put something useful in my_ptr, like the address of memory that will hold a structure 
allocate(&my_ptr); 

在這種情況下,要記住的重要一點是要傳遞指針的位置,而不是指針指向的數據的位置

+0

我明白這種方法中&符號的功能,但實際發生了什麼?我正在向一個指針(* ptr)請求一個指針(*),因此需要語法(** ptr)。我理解這部分。所以當我編寫'* ptr = malloc ...'時,我們基本上是將內存塊的地址分配給指針指向的任何地址嗎?也就是說,由於&my_ptr指向my_ptr,我們正在取消引用&my_ptr並將存儲在my_ptr中的值分配爲內存塊地址? – sherrellbc

+0

@sherrellbc我更新了一下我的描述和更多的解釋,看看是否有幫助。 – lurker

1

例如如果正在定義的結構類型這樣

typedef struct abc 
    { 
    int a; 
    char name[20]; 
    }abc_t; 

    int main() 
    { 
    abc_t *ptr=NULL; 
    allocate(&ptr); // you are passing address of pointer , call by reference 
        //things gets effected which made in function. 
    } 

您需要分配的沒有該abc_t類型的對象requires.To在功能分配存儲器的指針的字節需要定義函數與雙指針。

void allocate(abc_t **ptr) 
     { 
     *ptr=(abc_t *)malloc(sizeof(abc_t)); 
     } 
1
void allocate(structure *ptr){ 
    ptr = malloc(sizeof(ptr)); //ptr assigned memory block address 
} 

這裏,PTR是指向的結構。它存儲一組構成類「結構」的元素的地址。因此,sizeof(ptr)將返回用於存儲結構地址的字節數,但不返回結構本身的大小。因此,分配的內存來存儲1個單元構成,您需要修改語句,

void allocate(structure *ptr){ 
    ptr = malloc(sizeof(structure)); //ptr assigned memory block address 
} 

另外,爲了實現,你通過維持功能「無效」的返回類型說,你可以使用通話函數調用的引用機制。

void allocate(structure **ptr){ 
    *ptr = malloc(sizeof(structure)); //ptr assigned memory block address 
} 

調用者應該調用它,

allocate(&ptr);