zoukankan      html  css  js  c++  java
  • 深入理解 C 指针阅读笔记 -- 第六章

    Chapter6.h

    #ifndef		__CHAPTER_6_
    #define		__CHAPTER_6_
    
    /*《深入理解C指针》学习笔记 -- 第六章*/
    
    typedef struct __person
    {
    	char* name;
    	char* title;
    
    	unsigned int age;
    }person;
    
    /*结构体内存的释放问题*/
    void __struct_memory_test();
    
    #endif

    Chapter6.cpp

    #include "Chapter6.h"
    #include <stdio.h>
    #include <malloc.h>
    #include <string.h>
    
    /*结构体内存的释放问题*/
    /*对于结构体内存在指针的情况,我们须要注意如何正确的使用这个结构体*/
    void __struct_memory_test()
    {
    	/*第一种使用结构体的方式*/
    	person ps;
    
    	/*须要为结构体内的指针分配内存才干存储值*/
    	ps.name = (char*)malloc(sizeof(char) * 16);
    	strcpy(ps.name, "DLUTBruceZhang");
    
    	ps.title = (char*)malloc(sizeof(char) * 10);
    	strcpy(ps.title, "DLUT");
    
    	ps.age = 24;
    
    	/*使用完之后须要释放结构体指针的内存*/
    	free(ps.name);
    	free(ps.title);
    
    	/*另外一种使用结构体的方式*/
    	person* ps2;
    
    	/*
    		首先,须要为结构体申请内存,可是这里须要注意的是,仅仅是为这个结构体申请
    		内存。结构体内的其它指针须要另外申请别的内存
    	*/
    	ps2 = (person*)malloc(sizeof(person));
    
    	/*须要为结构体内的指针分配内存才干存储值*/
    	ps2->name = (char*)malloc(sizeof(char) * 16);
    	strcpy(ps2->name, "DLUTBruceZhang");
    
    	ps2->title = (char*)malloc(sizeof(char) * 10);
    	strcpy(ps2->title, "DLUT");
    
    	ps2->age = 24;
    
    	/*
    		使用完内存后须要释放掉,这里须要注意的是释放内存的顺序
    		首先应该释放结构体内指针指向的内存,这里是没有先后顺序的,
    		可是。释放整个结构体的内存一定是最后一步
    	*/
    	free(ps2->name);
    	free(ps2->title);
    
    	free(ps2);
    }


  • 相关阅读:
    考虑浏览器兼容的文件上传(IE8不支持FormData)
    IDEA tomcat 部署WEB项目
    如何在springcloud分布式系统中实现分布式锁?
    ABAP DEMO33 选择周的搜索帮助
    ABAP函数篇1 日期函数
    ABAP函数篇2 测试DATE_CONVERT_TO_FACTORYDATE
    增强篇7 判断标准屏幕能否做屏幕增强
    增强篇6 CMOD增强删除
    ABAP DEMO 年月的搜索帮助
    HoloLens开发手记-配置开发环境 Install the tools
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6808835.html
Copyright © 2011-2022 走看看