C函数中的指针赋值

use*_*197 5 c pointers function 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;
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

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
Run Code Online (Sandbox Code Playgroud)

Fle*_*exo 5

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;
}
Run Code Online (Sandbox Code Playgroud)