首页 > 数据库 > 数据库开发技术 > 二级指针做形参机制总结
本文对C 二级指针做形参的机制做了总结.
[@more@]很多 C programmer 对二级指针做形参比较困惑:
关于此,本人总结:
1 核心是地址和内容,要严格区分. 二级指针做形参更多用来完成两个地址空间(二个程序或二个DLL)之间的地址传递. 高级程序如Apache 多用这种方法来完成地址的传递.
2
3
重点符号:
如果对汇编知识了解点,就好理解了.
看我做的测试例子:
#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/ ,如需转载,请注明出处,否则将追究法律责任。