程序崩溃的原因

Why the program crashes?

本文关键字:崩溃 程序      更新时间:2023-10-16

此代码编译正确,但在启动时崩溃。你能告诉我为什么吗?

#include <iostream>
using namespace std;
int main()
{
    struct test{
        int a;
        int b;
    };
    test* xyz;
    xyz->a = 5;
    cout<< xyz->a;
}

xyz只是一个指针,但它不指向任何东西。在使用其值之前,必须先实例化它。你基本上有两个选择:

  1. 通过在堆上创建一个新的测试对象来实例化xyz。

    //generate new test object. xyz represents a pointer to an object of type test.
    test* xyz = new test();
    //perform operations on xyz
    //deletes xyz from the heap
    delete xyz;
    
  2. 在堆栈上创建一个测试对象,而不使用指针语法。

    //defines xyz as an object of class test (instead of a pointer to a test object).
    test xyz;
    //perform operations on xyz, no need to delete it this time
    

我鼓励您阅读更多关于C++中指针的内容。您可以从以下视频开始:C++中指针的介绍

祝你好运!