程序崩溃的原因是什么?

时间:2016-03-27 18:09:56

标签: c++ struct

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

#include <iostream>
using namespace std;

int main()
{
    struct test{
        int a;
        int b;
    };

    test* xyz;

    xyz->a = 5;

    cout<< xyz->a;
}

1 个答案:

答案 0 :(得分:1)

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
    
  3. 我鼓励您阅读有关C ++中指针的更多信息。 您可以从以下视频开始:  Introduction to Pointers in C++

    祝你好运!

相关问题