zoukankan      html  css  js  c++  java
  • C/C++ 错误笔记-在给结构体中的指针赋值时,要注意该指针是否已指向内存空间

    先来看下面的例子:

    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>
    
    #pragma warning(disable:4996)
    
    typedef struct _Student
    {
        char name[64];
        int age;
    
    }Student;
    
    
    typedef struct _Teacher
    {
        char name[64];
        int age;
        char *p1;
        char **p2;
        Student s1;
        Student *ps1;
    
    }Teacher;
    
    
    
    int main()
    {
    
        Teacher t1;
        t1.age = 30;
        t1.s1.age = 20;
    
        // 操作结构体中的结构体指针
        t1.ps1->age = 100;
    
        system("pause");
        return 0;
    }

    编译,没有问题,但是一运行,程序直接报错

    问题出现在

    t1.ps1->age = 100; 这一行,因为我们在给结构体指针Student的age属性赋值时,并未给ps1指针开辟内存空间,所以相当于给一个空指针赋值,因此程序crash掉了。

    下面是修改后的代码:

    int main()
    {
    
        Teacher t1;
        Student s1;
        t1.age = 30;
        t1.s1.age = 20;
    
        // 操作结构体中的结构体指针
        t1.ps1 = &s1;
        t1.ps1->age = 100;
    
        system("pause");
        return 0;
    }

    我们在给ps1的age属性赋值时,已为ps1指向了一块内存空间,这样程序就不会再crach了。因此在使用指针时需要记得一句话:

    没有内存,哪来的指针? 

  • 相关阅读:
    Channel使用技巧
    Flask开发技巧之异常处理
    后端开发使用pycharm的技巧
    python单元测试
    Docker入门介绍
    python高阶函数的使用
    python内置模块collections介绍
    python中@property装饰器的使用
    三次握手四次挥手
    python类方法@classmethod与@staticmethod
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/6953268.html
Copyright © 2011-2022 走看看