指针笔试题(一)

#include <iostream>
void GetMemory(char *p,int num)
{
 p=(char *)malloc(sizeof(char)*num);
}
int main()
{
  char *str=NULL;
  GetMemory(str,100);
  strcpy(str,"hello");
  return 0;

}

注:p申请了新内存,只是把p所指的内存地址改变了,但是str丝毫未变。

所以每次GetMemory就会申请一块内存,但申请的内存却不能有效释放,结果是内存一直被独占,最终造成内存泄漏。


变形一:

#include <iostream>
using namespace std;
void GetMemory(char **p,int num)
{
 *p=(char *)malloc(sizeof(char)*num);
}
int main()
{
  char *str=NULL;
  GetMemory(&str,100);
  strcpy(str,"hello");
  return 0;
}

注:传指向指针的指针,传str的地址给函数GetMemory,就行了。

*str      str      &str   

h       hello   0x22f7c

字符串某一字符的值     字符串的值   字符串的地址值  


再变形:

#include <iostream>
using namespace std;
char *GetMemory(char *p,int num)
{
 p=(char *)malloc(sizeof(char)*num);
 return p;
}
int main()
{
  char *str=NULL;
  str=GetMemory(str,100);
  strcpy(str,"hello");
  cout<<str<<endl;
  return 0;
}

注:用函数返回值来传递动态内存。


#include <iostream>
using namespace std;
void GetMemory(int *z)
{
*z=5;
}
int main()
{
int v;
GetMemory(&v);
cout<<v<<endl;
return 0;
}

注:通过传地址,GetMemory函数给地址指向的值赋值,可以实现。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值