牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2014-10-25 投稿人: 浏览次数:445
 典型的错误例子如下

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

失败的例子

#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 ");
   exit(0);
}

}


int main()
{
char *str1=NULL;
fen_pei(str1,10);
strcpy(str1,"hello");
   printf("%s ",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 ");
   exit(0);
}
return p;
}


int main()
{
char *str1=NULL;
str1=fen_pei(str1,10);
strcpy(str1,"hello");
   printf("%s ",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 ");
   exit(0);
}

}


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

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

void fun(int *(&p))

{

p = new int;

.....   

}

int main()

{

........

int *q;

fun(q);

return 0;

}

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。