2016-03-27 214 views
-4

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

#include <iostream> 
using namespace std; 

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

    test* xyz; 

    xyz->a = 5; 

    cout<< xyz->a; 
} 
+2

未定义的行为?使用单元化指针,因此指向某处并且很可能不是您想要的 – JVApen

+0

*此代码编译正确,但在开始时崩溃。* - 仅仅因为您的程序编译正确并不意味着它会自动正确运行。 – PaulMcKenzie

+0

感谢知识@PaulMcKenzie –

回答

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 
    

我鼓励你在C阅读更多关于指针++。 你可以从以下视频开始: Introduction to Pointers in C++

祝你好运!