您的位置:首页 > 其它

双指针的常见用法

2017-06-14 09:08 253 查看
转自:http://blog.csdn.net/ceelo_atom/article/details/49505987

1、内存拷贝错误示例:

int  memory_malloc(char *pst ,unsigned int size)
{

if (size  == 0 )
{
pst = NULL;
return -1;
}

pst=(char *)malloc(size);

if(pst  == NULL)
{
printf("malloc failed.\n");
return -1;
}
return 0;

}

int main()
{
char *pstr = NULL;
char str[]="hello";

memory_malloc(pstr,sizeof(str));

if (pstr == NULL)
{
printf("pstr is NULL.\n");
// return  -1;
}

memcpy(pstr,str,sizeof(str));
printf("the str is %s .\n",pstr);
return 0;
}


    结果:程序运行时,打印出 "pstr is NULL." 后出现崩溃!!!!

错误原因:对内存进行了非法访问,调用memory_malloc 后,pstr指向的是NULL依然。pstr参数会进行拷贝给memory_malloc,

假设拷贝后的参数为_pstr,_pstr指向分配的堆空间,而pstr指向的任然是NULL。调用memory_malloc后,新分配的内存没发使用,还会导致内存泄漏。



2、正确的用法:

int  memory_malloc(char **pst ,unsigned int size)
{

if (size  == 0 )
{
pst = NULL;
return -1;
}

(*pst)=(char *)malloc(size);

if(pst  == NULL)
{
printf("malloc failed.\n");
return -1;
}
return 0;

}

int main()
{
char *pstr = NULL;
char str[]="hello";

memory_malloc(&pstr,sizeof(str));

if (pstr == NULL)
{
printf("pstr is NULL.\n");
// return  -1;
}
memcpy(pstr,str,sizeof(str));

printf("the str is %s .\n",pstr);

return 0;
}
传入的是pstr的地址,传入函数后进行引用操作,则可以对pstr实际地址进行操作。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  双指针 C