您的位置:首页 > 其它

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

2012-10-11 22:08 232 查看


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

(2011-06-07 13:41:53)


转载▼


标签:


杂谈

分类: C
典型的错误例子如下

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

失败的例子

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: