• c语言结构体指针初始化


         今天终于看完了C语言深度剖析这本书,对C语言有了进一步的了解与感悟,突然发觉原来自己学C语言的时候学得是那样的迷糊,缺少深入的思考,在重新看书的时候发觉C语言基本教材虽然经典,但是缺乏独到性,老师在讲解的过程中也就照本宣科了,没有多大的启迪。

         看到C语言内存管理这块,发觉还是挺有用的,当然平时在编程时基本上就没有考虑过内存问题。

         定义了指针变量,没有为指针分配内存,即指针没有在内存中指向一块合法的内存,尤其是结构体成员指针未初始化,往往导致运行时提示内存错误。

    #include "stdio.h"
    #include "string.h"
    
    struct student
    {
           char *name;
           int score;
           struct student *next;      
    }stu, *stul;
    
    int main()
    {
           strcpy(stu.name,"Jimy");   
           stu.score = 99;  
           return 0;
    }

    由于结构体成员指针未初始化,因此在运行时提示内存错误

    #include   “stdio.h” 
    #include   "malloc.h"
    #include   "string.h"
      
    struct student
    {   
        char *name;   
        int score;   
        struct student* next;   
    }stu,*stu1;    
      
    int main()
    {    
        stu.name = (char*)malloc(sizeof(char)); /*1.结构体成员指针需要初始化*/  
        strcpy(stu.name,"Jimy");   
        stu.score = 99;   
        
        stu1 = (struct student*)malloc(sizeof(struct student));/*2.结构体指针需要初始化*/  
        stu1->name = (char*)malloc(sizeof(char));/*3.结构体指针的成员指针同样需要初始化*/  
        stu.next  = stu1;   
        strcpy(stu1->name,"Lucy");   
        stu1->score = 98;   
        stu1->next = NULL;   
        printf("name %s, score %d 
     ",stu.name, stu.score);   
        printf("name %s, score %d 
     ",stu1->name, stu1->score);   
        free(stu1);   
        return 0;   
    }  

    同时也可能出现没有给结构体指针分配足够的空间

        stu1 = (struct student*)malloc(sizeof(struct student));/*2.结构体指针需要初始化*/ 

    如本条语句中往往会有人写成

        stu1 = (struct student*)malloc(sizeof(struct student *));/*2.结构体指针需要初始化*/ 

    这样将会导致stu1的内存不足,因为sizeof(struct student)的长度为8,而sizeof(struct student *)的长度为4,在32位系统中,编译器默认会给指针分配4字节的内存

  • 相关阅读:
    初拾Java(问题一:404错误,页面找不到)
    新年新气象--总结过去,展望未来
    接口测试[整理]
    [转]SVN-版本控制软件
    浅谈黑盒测试和白盒测试
    Bug管理工具的使用介绍(Bugger 2016)
    P2805/BZOJ1565 [NOI2009]植物大战僵尸
    近期学习目标
    P3643/BZOJ4584 [APIO2016]划艇
    P5344 【XR-1】逛森林
  • 原文地址:https://www.cnblogs.com/lijumiao/p/3624066.html
Copyright © 2020-2023  润新知