利用函数 分配空间,返回指针

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *GetMemory(int size)//函数指针  *不能少
{
char *a=NULL;
a=(char *)malloc(sizeof(100));
return a;
}
void get(char **str,int size)
{
*str=(char *)malloc(sizeof(100));
}
void fun(char *str)
{
strcpy(str,"1789");
}
char *func(void)
{
char *p;
p=(char *)malloc(sizeof(128));
strcpy(p,"hello world");
return p;
}
int main()
{
char *x=NULL;
x=(char *)malloc(sizeof(128));
x=func();
printf("%s\n",x);
free(x);
x=NULL;
//1.在一个函数中申请和释放
char *p=NULL;
p=(char *)malloc(sizeof(100));
strcpy(p,"helloworld");
printf("%s\n",p);
free(p);
p=NULL;

//2.在一个子函数中分配
char *s=NULL;
s=GetMemory(100);
strcpy(s,"123456");
printf("%s\n",s);
free(s);
s=NULL;

//3.从一个子函数的参数返回内存,不通过return的方式
char *q=NULL;
get(&q,100);
strcpy(q,"qqqq");
printf("%s\n",q);
free(q);
q=NULL;

char *w=NULL;
w=(char *)malloc(sizeof(100));
fun(w);
printf("%s\n",w);
free(w);
w=NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值