zoukankan      html  css  js  c++  java
  • [C语言] 数据结构-预备知识跨函数使用内存

    跨函数使用内存
    一个函数运行结束,使用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);
    }
  • 相关阅读:
    第09组 Alpha冲刺 (6/6)
    第09组 Alpha冲刺 (5/6)
    第09组 Alpha冲刺 (4/6)
    第09组 Alpha冲刺 (3/6)
    第09组 Alpha冲刺 (2/6)
    第09组 Alpha冲刺 (1/6)
    第9组(71) 需求分析报告
    第9组(71) 团队展示
    结对编程作业
    第08组 Alpha冲刺 总结
  • 原文地址:https://www.cnblogs.com/taoshihan/p/8366233.html
Copyright © 2011-2022 走看看