2013-09-05 43 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);