指针变量传递给函数

来源:互联网 发布:淘宝上发票抬头写个人 编辑:程序博客网 时间:2024/04/28 06:57

  大家都知道,指针变量存储的地址,但是,在进行函数调用的时候,大家有想过能否将指针变量本身传递给一个函数了?

这里首先给大家纠正一个错误,其实main函数内部声明的变量也是局部变量,它们也只是在main函数内部有效,只不过是它们的生命周期和全局变量一样长而已。全局变量一定是定义在函数外部的

  好了,现在大家知道了--------无法把指针变量本身传递给一个函数。测试一下:

#include <stdlib.h>#include <stdlib.h>#include <string.h>void allocate_mem(char *p, int n){p = (char *)malloc(n * sizeof(char));}int main(void){char *dst = NULL;allocate_mem(dst, 20);strcpy(dst, "I love Linux");free(dst);return 0;}

  经测试,单步调试执行到strcpy函数时出现:No source available for "memcpy() at 0x5263f46" (以上测试在Fedora9 eclipse环境下)。观察得到dst的值仍然为NULL,说明malloc函数动态分配的内存没有赋给dst,而是赋给了dst一个备份,而这个备份是随编译器自动分配和回收的,当allocate_mem函数调用结束,这个备份也就被释放。


那么怎样获得一块内存区了?

1、用指针函数实现

#include <stdlib.h>#include <string.h>#include <stdio.h>char *allocate_mem(char *p, int n){p = (char *)malloc(n * sizeof(char));return p;}int main(void){char *dst = NULL;dst = allocate_mem(dst, 20);strcpy(dst, "I love Linux");free(dst);return 0;}

2、用二级指针实现

#include <stdlib.h>#include <string.h>#include <stdio.h>void allocate_mem(char **p, int n){*p = (char *)malloc(n * sizeof(char));}int main(void){char *dst = NULL;allocate_mem(&dst, 20);strcpy(dst, "I love Linux");free(dst);return 0;}

  这里很显然,参数是&dst,而不是dst指针变量,这样传递是地址,而非dst变量本身。