主程序和子程序 分配新指针

来源:互联网 发布:曲面软件 编辑:程序博客网 时间:2024/06/07 03:31

主程序:

#include <stdio.h>#include <malloc.h>int main(int argc, char *argv[]){char* p = (char*)malloc(sizeof(char)*100);printf("addr of p is: 0x%x\n",p);free(p);return 0;}
注意malloc的写法,最后要free。
子程序:

#include <stdio.h>#include <malloc.h>void fun(char** p){*p = (char*)malloc(sizeof(char)*100);printf("addr of p is: 0x%x\n",*p);free(*p);}int main(int argc, char *argv[]){char* p = NULL;fun(&p);return 0;}

注意调用子程序fun时,传入的是指针的地址,在子程序里操作的是指针地址的副本,这个副本一样指向指针所在的地址单元。不能直接传入指针,这和做数值交换时,不能直接传入数值是一样的道理。
0 0