2011-12-03 31 views
1
#include <iostream> 
#include <string> 
#include <list> 
#include <conio.h> 
using namespace std; 

class people 
{ 
public: 

    people* p; 
    int x; 
    people(); 
}; 
people::people() 
{ 
    p = NULL; 
} 
void main() 
{ 

    people jax; 
    jax.p->x = 1; 

} 

我classarray.exe在0x00361419得到這個錯誤在C定義類的指針++

未處理的異常:0000005:訪問衝突寫入位置0x00000004。

在這一行 jax.p->x = 1;

幫我請!

+2

'jax.p'is一個空指針,你能指望什麼,當您嘗試訪問它會發生什麼? – Thomas

+0

更好的定義構造函數'people :: people():p(NULL){}'來提高效率。 –

+2

'void main()'在C++中是非法的。 –

回答

2

你需要保留內存人羣:

void main() 
{ 

    people jax; 
    jax.p=new people; 
    jax.p->x = 1; 
    ... 

    delete jax.p; 

} 

編輯:在你需要釋放你的記憶,或者你將有內存泄漏結束 。

1

另一種方式是實現特殊功能的內部指針初始化:

void people::init_p() 
{ 
    if(!p) p = new people(); 
}