指针参数是如何传递内存的?

(1)如果函数的参数是一个指针,不要指望用该指针去申请动态内存。

#include <stdlib.h>

#include <string.h>

 

void GetMemory(char *p,int num)

{

       p=(char *)malloc(sizeof(char)*num);//内存泄露

}

 

void Test(void)

{

       char *str=NULL;

       GetMemory(str,100);//str仍然为NULL

       strcpy(str,"hello");

}

void main()

{

       Test();

}

(2)指向指针的指针

#include <stdlib.h>

#include <string.h>

#include <iostream.h>

 

void GetMemory2(char **p,int num)

{

       *p=(char *)malloc(sizeof(char)*num); //内存泄露

}

 

void Test(void)

{

       char *str=NULL;

       GetMemory2(&str,100);

       strcpy(str,"hello");

       cout<<str<<endl;

}

 

void main()

{

       Test();

}

 (3)函数返回值来传递动态内存

#include <stdlib.h>

#include <string.h>

#include <iostream.h>

 

char *GetMemory3(int num)

{

       char *p=(char *)malloc(sizeof(char)*num); //内存泄露

       return p;

}

 

void Test(void)

{

       char *str=NULL;

       str=GetMemory3(100);

       strcpy(str,"hello");

       cout<<str<<endl;

}

 

void main()

{

       Test();

}

 

不要用return语句返回指向"栈内存"的指针,因为该内存在函数结束时自动消亡

#include <stdlib.h>

#include <string.h>

#include <iostream.h>

 

char *GetString(void)

{

       char p[]="hello world";//在栈上被创建

       return p;

}

 

void Test(void)

{

       char *str=NULL;

       str=GetString();//str的内容是垃圾

       cout<<str<<endl;

}

void main()

{

       Test();

}

 

 

设计概念错误

#include <stdlib.h>

#include <string.h>

#include <iostream.h>

char *GetString2(void)

{

       char *p="hello world";//指针p指向常量字符串"hello world"

       return p;

}

 

void Test(void)

{

       char *str=NULL;

       str=GetString2();

       cout<<str<<endl;

}

void main()

{

       Test();

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值