## 在子函数中给main函数指针分配内存的方法
错误的方法:
```cpp
#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;
}
```
这种方法的思路是 主函数中生成一个指针 ->将这个指针发送给子函数 ->子函数给这个指针分配对应的内存
但是存在一个问题,c语言中如果发送一个变量给函数,函数是改变不了这个变量的值的,当这个变量变成指针时同样如此,函数改变不了这个指针上的值。
因此如果要让子函数给主函数的指针分配内存空间,就需要发送原指针的地址。
正确做法:
```cpp
#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;
}
```
当主函数给子函数发送指针的地址时,子函数就可以改变指针的值了(指向的内存空间)。
还有另一种可行的方法:
```cpp
#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;
}
```
这种方法是将(子函数中指向需要开辟内存空间的指针)返回给主函数。