C函数中的指针赋值

时间:2013-02-07 20:24:25

标签: c function pointers variable-assignment

为什么我不能在函数中指定一个点。正如您在以下代码中注意到的那样。函数返回后,我无法将指针p1指向正确的地址。但是使用全局指针* p,我可以存储地址信息。

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

int *p = NULL;
void test(int * pt1, int**pt2){
    p = (int*)malloc(sizeof(int));    
    pt1 = p;
    *pt2 = p;
    printf("p points to %p\n", p);
    printf("pt1 points to %p\n", pt1);
    printf("pt2 points to %p\n", *pt2);
}

int main(void) {
    int *p1 = NULL; 
    int *p2 = NULL;

    printf("p points to %p\n", p);
    printf("p1 points to %p\n", p1);
    printf("p2 points to %p\n", p2);

    test(p1, &p2);

    printf("p points to %p\n", p);
    printf("p1 points to %p\n", p1);
    printf("p2 points to %p\n", p2);

    return 0;
}

输出:

p points to (nil)
p1 points to (nil)
p2 points to (nil)
p points to 0x8acb008
pt1 points to 0x8acb008
pt2 points to 0x8acb008
p points to 0x8acb008
p1 points to (nil)
p2 points to 0x8acb008

3 个答案:

答案 0 :(得分:4)

test内,变量pt1本身就是一个离散指针。也就是说,仅仅是p1的别名,而是仅在呼叫的生命周期内存在的副本。

因此,您对其所做的任何分配仅在该呼叫的持续时间内退出,并且不会在其外部传播。当您从test返回时,指针pt1不再存在,并且不会复制任何更改。

除了像使用pt2一样使用指针的额外“图层”时,有时使用返回值与更广泛的受众“共享”更改是合适的:

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

int *p = NULL;
int *test(int * pt1, int**pt2){
    p = (int*)malloc(sizeof(int));    
    pt1 = p;
    *pt2 = p;
    printf("p points to %p\n", p);
    printf("pt1 points to %p\n", pt1);
    printf("pt2 points to %p\n", *pt2);
    return pt1;
}

int main(void) {
    int *p1 = NULL; 
    int *p2 = NULL;

    printf("p points to %p\n", p);
    printf("p1 points to %p\n", p1);
    printf("p2 points to %p\n", p2);

    p1=test(p1, &p2);

    printf("p points to %p\n", p);
    printf("p1 points to %p\n", p1);
    printf("p2 points to %p\n", p2);

    return 0;
}

答案 1 :(得分:1)

您正在通过值传递p1,因此更改仅在该函数的范围内可见。传递指向该指针的指针,就像你对p2所做的那样,你很好。

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

int *p = NULL;
void test(int **pt1, int**pt2){
    p = (int*)malloc(sizeof(int));    
    *pt1 = p;
    *pt2 = p;
    printf("p points to %p\n", p);
    printf("pt1 points to %p\n", pt1);
    printf("pt2 points to %p\n", *pt2);
}

int main(void) {
    int *p1 = NULL; 
    int *p2 = NULL;

    printf("p points to %p\n", p);
    printf("p1 points to %p\n", p1);
    printf("p2 points to %p\n", p2);

    test(&p1, &p2);

    printf("p points to %p\n", p);
    printf("p1 points to %p\n", p1);
    printf("p2 points to %p\n", p2);

    return 0;
}

答案 2 :(得分:1)

您按值传递p1,因此未在main函数中更新。但是,您通过引用传递p2(请注意您编写了&p2),因此可以更改它。