zoukankan      html  css  js  c++  java
  • 数据结构复习之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);
    }
  • 相关阅读:
    进程池和线程池
    TCP并发、GIL、锁
    进程间通信
    装饰器与反射
    装饰器大全
    面向对象三大特征: 封装 继承 多态
    面向对象 魔术方法
    魔术方法
    ubuntu 中导 tarfile,win 不亲切
    os VS shutil
  • 原文地址:https://www.cnblogs.com/lqcdsns/p/6582066.html
Copyright © 2011-2022 走看看