关于调用子函数给主函数指针分配内存


典型的错误例子如下

在这个主函数的指针给子函数传递一个指针,而在子函数中形参有开辟了一块内存,此子函数的指针的内存里存储的地址与主函数是同一地址,即主函数的指 针和子函数形参的指针都指向同一块内存的地址,但是在子函数里,为子函数的指针申请了一块空间,并不影响主函数的指针。因为子函数的指针又指向了别的内 存。要想分配成功就得用下面两个例子。一个是在子函数的形参中第一指向指针的指针即二级指针,叫子函数的指针指向实参的指针,另外一种方法就是返回子函数 分配完内存的指针。

失败的例子

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


fen_pei(char *p,int n)
{
p=(char *)malloc(n*sizeof(char *));
if(p==NULL)
{
   printf("allocation failture\n");
   exit(0);
}

}


int main()
{
char *str1=NULL;
fen_pei(str1,10);
strcpy(str1,"hello");
   printf("%s\n",str1);
  
   return 0;
}

成功的方法1,返回分配内存的指针

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


char *fen_pei(char *p,int n)
{
p=(char *)malloc(n*sizeof(char *));
if(p==NULL)
{
   printf("allocation failture\n");
   exit(0);
}
return p;
}


int main()
{
char *str1=NULL;
str1=fen_pei(str1,10);
strcpy(str1,"hello");
   printf("%s\n",str1);
  
   return 0;
}

成功的方法2.,在子函数形参中使用指向指针的指针

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


void fen_pei(char **p,int n)
{
*p=(char *)malloc(n*sizeof(char *));
if(p==NULL)
{
   printf("allocation failture\n");
   exit(0);
}

}


int main()
{
char *str1=NULL;
fen_pei(&str1,10);
strcpy(str1,"hello");
   printf("%s\n",str1);
  
   return 0;
}

成功的方法3,在C++中还可以使用引用。

void fun(int *(&p))

{

p = new int;

.....   

}

int main()

{

........

int *q;

fun(q);

return 0;

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值