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

来源:互联网 发布:拼多多客服软件 编辑:程序博客网 时间:2024/05/17 10:29

典型的错误例子如下

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

失败的例子

#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 0
原创粉丝点击