• 数据结构复习之C语言malloc()动态分配内存概述


    #include <stdio.h>
    #include <malloc.h>
    
    int main(void)
    {
        int a[5] = {4, 10, 2, 8, 6};
        // 计算数组元素个数
        int len = sizeof(a)/sizeof(a[0]);
        int i;
    
        //printf("%d", len);
    
        // sizeof(int) int类型的字节数
        // 动态分配内存
        // malloc返回第一个字节的地址
        int *pArr = (int *)malloc(sizeof(int) * len);
    
        for(i = 0; i < len;i++)
            scanf("%d", &pArr[i]);
    
        for(i = 0; i < len;i++)
            printf("%d
    ", *(pArr + i));
    
        free(pArr); // 把pArr所代表的动态分配的20个字节的内存释放
    
        return 0;
    }

    跨函数使用内存
    函数内的局部变量,函数被调用完之后,变量内存就没有了。
    如果是一个动态的变量,动态分配的内存必须通过free()进行释放,不然只有整个程序彻底结束的时候
    才会释放。
    跨函数使用内存实例:

    #include <stdio.h>
    #include <malloc.h>
    
    struct Student
    {
        int sid;
        int age;
    };
    
    struct Student *CreateStudent(void);
    
    int main(void)
    {
        struct Student *ps;
    
        ps = CreateStudent();
        ShowStudent(ps); // 输出函数
    
        return 0;
    }
    
    struct Student *CreateStudent(void)
    {
        // sizeof(struct Student) 结构体定义的数据类型所占用的字节数
        struct Student *p = (struct Student *)malloc(sizeof(struct Student)); // 创建
        // 赋值
        p->sid = 99;
        p->age = 88;
        return p;
    };
    
    void ShowStudent(struct Student *pst)
    {
        printf("%d %d
    ", pst->sid, pst->age);
    }
  • 相关阅读:
    线段树(segment tree)
    外排序
    【机器学习】如何成为当下合格的算法工程师
    Result Maps collection already contains value for
    负向零宽断言
    正则匹配中 ^ $ 和  的区别
    jq异步上传文件(转载)
    js触发按钮点击事件
    ./ ,../ , 以及/的区别
    eclipse遇到不会部署的情况
  • 原文地址:https://www.cnblogs.com/lqcdsns/p/6582066.html
Copyright © 2020-2023  润新知