ITPub博客

首页 > 数据库 > 数据库开发技术 > 二级指针做形参机制总结

二级指针做形参机制总结

原创 数据库开发技术 作者:jamescodd 时间:2009-01-04 11:49:08 0 删除 编辑

本文对C 二级指针做形参的机制做了总结.

[@more@]

很多 C programmer 对二级指针做形参比较困惑:

关于此,本人总结:

1 核心是地址和内容,要严格区分. 二级指针做形参更多用来完成两个地址空间(二个程序或二个DLL)之间的地址传递. 高级程序如Apache 多用这种方法来完成地址的传递.

2 实参和形参的地址空间是单独分配的.但形参的地址可以指向实参,在函数调用期间可以把获得的地址反向传递给实参.

3 实参向形参传递参数核心都是"值"拷贝! 即 取一级引用内容. 看压栈的值是普通变量、一级指针、二级指针.

重点符号: char * str; 那么三要素是 &str(自身地址) str(间接地址) *str(间接引用) 要严格区分.

如果对汇编知识了解点,就好理解了.

看我做的测试例子:

#include
#include
#include
void GetMemory(char *p, int num)
{
printf("pre-0x%xn",&p);
printf("pre-0x%xn",p);
p = (char *)malloc(sizeof(char) * num);
printf("after-0x%xn",&p);
printf("after-0x%xn",p);
}
void Test(void) //此函数产生内存泄露
{
char *str = NULL;
printf("caller-0x%xn",&str);
GetMemory(str, 100); // str 仍然为 NULL
printf("caller-0x%xn",&str);
if(str!=NULL)
strcpy(str, "hello"); // 运行错误
}
void GetMemory2(char **p, int num)
{
printf("before(&p)-0x%xn",&p);
printf("before(p)-0x%xn",p);
printf("before(*p)-0x%xn",*p);
*p = (char *)malloc(sizeof(char) * num);
printf("after(&p)-0x%xn",&p);
printf("after(p)-0x%xn",p);
printf("after(*p)-0x%xn",*p);

}
void testinter(int **m)

{
printf("in stack=0x%xn",&m);
printf("in stack=0x%xn",m);
*m=(int*)malloc(sizeof(int));
**m=3;
}

void Test3(void)
{

int *p2=NULL;

testinter(&p2);

printf("after=0x%xn",&p2);
printf("after=0x%xn",p2);
printf("after=%dn",*p2);

}
void Test2(void)
{

char *str = NULL;
printf("caller(&str)-0x%xn",&str);
GetMemory2(&str, 100); // 注意参数是 &str,而不是str
printf("caller(&str)-0x%xn",&str);
printf("caller(str)-0x%xn",str);
if(str!=NULL)strcpy(str, "hello ok!!!!!n");
printf("%s",str);
free(str);
}
void main()
{

//分别测试.
//Test();
Test2();
//Test3();
}

运行结果:Test3:

----------------------------

in stack=0x13fed8
in stack=0x13ff28
after=0x13ff28
after=0x30fe0
after=3
------------------------------

Test2:

caller(&str)-0x13ff28
before(&p)-0x13fed4
before(p)-0x13ff28
before(*p)-0x0
after(&p)-0x13fed4
after(p)-0x13ff28
after(*p)-0x30fe0
caller(&str)-0x13ff28
caller(str)-0x30fe0
hello ok!!!!!
-----------------------------------

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/784596/viewspace-1015634/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2012-04-09

  • 博文量
    11
  • 访问量
    157961