2011-09-26 17 views
1

有人可以告訴我爲什麼會出現分段錯誤?我嘗試和一個指向數組對象的數組,我該如何解決這個問題? sf :: Vector2類的聲明可以在這裏找到:http://www.sfml-dev.org/documentation/1.6/classsf_1_1Vector2.php嘗試通過指針索引對象數組的數組時出現分段錯誤

非常感謝。

#include <SFML/System/Vector2.hpp> 
#include <iostream> 
class Tet 
{ 
    public: 
     Tet(); 
    private: 
     static sf::Vector2 <int> I[4]; 
     static sf::Vector2 <int> J[4]; 
     static sf::Vector2 <int> *types[2]; 

}; 

sf::Vector2 <int> Tet::I[4] = {sf::Vector2 <int>(0,1), 
           sf::Vector2 <int>(1,1), 
           sf::Vector2 <int>(2,1), 
           sf::Vector2 <int>(3,1)}; 

sf::Vector2 <int> Tet::J[4] = {sf::Vector2 <int>(1,1), 
           sf::Vector2 <int>(2,1), 
           sf::Vector2 <int>(3,1), 
           sf::Vector2 <int>(3,2)}; 

sf::Vector2 <int>* Tet::types[2] = { I,J };         

Tet::Tet() 
{ 
    //trying to print out x member of first vector of I 
    std::cout << (*(*(types))).x << std::endl; 
} 

main() 
{ 
    Tet t = Tet(); 
} 

編輯:G ++編譯器

+0

什麼是SF :: Vector2以及它是如何實現的初始化?只要看看代碼就會認爲它應該可以工作。你可以用更廣泛的類型來重現這一點,因爲如果沒有訪問sf :: Vector2,任何人都不可能採取這種做法並嘗試一下。 – Chad

+1

正如所料,一個簡單的例子(用char代替sf :: Vector2 )似乎有效。 – Chad

+0

它在這裏定義http://www.sfml-dev.org/documentation/1.6/Vector2_8hpp_source.php – aultbot

回答

1

你永遠不分配或實例化types陣列您引用。 types是一個指針,您不能將具體值分配給nullptr,這是您此刻如何離開它的原因。

就宣佈它爲一個數組,而不是一個指針 sf::Vector2<int> types[2][4];

您可能希望由具有Vector2對象,Matrix對象,然後Tet對象,它具有收藏也許是考慮一種更簡單更有效的設計使用STL容器和算法的矩陣。

+0

謝謝。我希望能夠索引types數組並返回I或J,這取決於僞隨機數生成器返回的索引值(0或1) – aultbot

+0

您可能對數組最好,並將指針留在此外那麼你不需要擔心內存管理。 – AJG85

+0

我想我可以聲明sf :: Vector2 的二維數組,然後改爲像sf :: Vector2 [2] [4] – aultbot

1

也許首先分配的類型,並{&我,&Ĵ}

相關問題