首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[C语言] 数据结构-预备知识跨函数使用内存

[C语言] 数据结构-预备知识跨函数使用内存

作者头像
唯一Chat
发布2019-09-10 13:02:57
3660
发布2019-09-10 13:02:57
举报
文章被收录于专栏:陶士涵的菜地陶士涵的菜地

跨函数使用内存 一个函数运行结束,使用malloc函数分配的内存,如果不调用free,就不会释放 在另一个函数中还可以继续使用

#include <stdio.h>
#include <malloc.h>
//跨函数使用内存
//传递结构体指针,占用内存少
struct Student {
        int age;
        int score;
        char *name;
};
struct Student * createStudent(struct Student *);//前置申明
void showStudent(struct Student *);
int main(void){
        struct Student *pst;//定义,当前只占4个字节
        pst=createStudent(pst);//创建,分配内存
        showStudent(pst);//展示,继续使用上面的内存
}
struct Student * createStudent(struct Student *pst){
        pst=(struct Student *)malloc(sizeof(struct Student));//给这个结构体分配内存,返回了指针
        pst->age=100;//结构体成员赋值
        pst->score=9999;
        pst->name="taoshihan";
        return pst;
}
void showStudent(struct Student *pst){
        //继续使用上面函数中分配的内存
        printf("%s  ===  %d === %d ",pst->name,pst->age,pst->score);
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-01-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档