C指针的疑惑(函数传址调用,如果传递的指针没有初始化会怎么样?)

来源:互联网 发布:163企业邮箱需要域名 编辑:程序博客网 时间:2024/04/28 07:55

有下列简单的C程序,想一想程序运行的结果是什么?
#include<stdio.h>
#include<stdlib.h>
int *p;
//p=NULL    (1)
void test_p(int *p){
    p=(int *)malloc(sizeof(int));
    if(!p){
        perror("malloc faild/n");
    }else{
        printf("in test_p *p=%d/n“,*p=3);
    }
}
void init_p(){
    p=(int *)malloc(sizeof(int));
    if(!p){
        perror("in init_p malloc faild/n");
    }else{
        printf("in init_p p=%X *p=%d/n",(unsigned)p,*p=4);
    }
}
int main(){
    test_p(p);
    if(!p){
        printf("after executed test_p p is NULL/n");
    }else{
        printf("after executed test_p *p=%d/n",*p=4);
    }
    return 0;
}

1)    输出结果是:
    in test_p *p=3
    after executed test_p p is NULL
    为什么?
2)    如果我将//p=NULL的注释去掉,编译能够通过吗?
    不能!
3)    修改main函数中的if...else代码块为
    printf("p is %X/n",(unsigned)p);
    输出为p is 0,在大多数编译器中,都使用0来表示NULL。
4)    如果不掉用test_p而调用init_p呢?
    显然结果是在init_p内外p都被初始化了。