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

来源:互联网 发布:淘宝男生裤子 编辑:程序博客网 时间:2024/05/22 16:56

典型的错误例子如下

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

失败的例子

#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;
}

理解:传递指针,其实传递的一个指针副本。

0 0
原创粉丝点击