指针问题

时间:2009-08-05 02:52:12

标签: c pointers stack-unwinding

好的,我通过2层函数fun1调用func2调用func3。我使用基本上int * ptr一直向下传递一个指针,在调用堆栈的最低“级别”我还有另一个为int数组动态分配内存的函数。在顶层(func1级别),我总是为传递的指针返回null。我已经追溯到func3并且分配的内存正在填充值,但是当调用堆栈展开func3 - > func2突然指针消失了(0x0000_0000)?我不明白在func3级别我基本上说ptr = allocate_ptr_array,但从那个返回它变为NULL!即使我没有释放记忆,世界上还在发生什么?我知道我的问题令人困惑。我已经在调试器中看到了这种情况,但

3 个答案:

答案 0 :(得分:6)

指针基本上是按值传递的。您需要将指针传递给指针(int ** p)以获取在外部函数中分配的内存。

function1(int *p)
{
 p = //allocate memory using malloc
}

function2(int **p)
{
 *p = //allocate memory using malloc
}

function3()
{
 int *p;
 function1(p); 
// in this case pointer is passed by value. 
//The memory allocated will not be available in p after the function call function1.

int **p;
function2(&p); 
//in this case pointer to pointer p has been passed.
// P will have the memory allocated even after 
//the function call function1
}

}

答案 1 :(得分:2)

用一些代码照亮aJ(完全正确)答案:

void func1(void)
{
    int *int_array;

    func2(&int_array);

    /* Some stuff using int_array[0] etc */

    /* ... */

    free(int_array);
}

void func2(int **a)
{
     /* ... stuff ... */

     func3(a);

     /* .... stuff ... */
}

void func3(int **a)
{
    (*a) = malloc(N * sizeof **a);
}

答案 2 :(得分:0)

以下是其他人未来参考的好例子。实施后这很有意义,感谢这些人。

#include <memory.h>
#include <stdlib.h>
#include <stdio.h>

void func3(int **ptr)
{
    int i;
    (*ptr) = (int *)malloc(25*sizeof(int));

    for (i=0; i < 25; i++) (**ptr) = i;
    printf("func3: %d\n",ptr);
}

void func2(int **ptr)
{
    func3(ptr);
    printf("func2: %d\n", ptr);
}
void func1(void)
{
    int *ptr;
    printf("ptr before: %d\n", ptr);
    func2(&ptr);
    printf("ptr after: %d\n", ptr);
}

void func4(int **ptr)
{
    static int stuff[25];
    printf("stuff: %d\n",stuff);
    *ptr = stuff;
}

int main(void)
{
    int *painter;
    func1();
    func4(&painter);
    printf("painter: %d\n", painter);
    return 0;
}
相关问题