2014-03-05 66 views
-2

我試圖創建一個Game結構,並通過這樣的構造函數中設置n玩家在裏面:不能與指針訪問指針結構,C++

typedef struct _Player 
{ 
    int life; 
    _Player() 
    { 
     life = 3; 
    } 
}Player; 

typedef struct _Game 
{ 
    Player **players; 
    _Game(int n) 
    { 
     *players = new Player[n]; 
     for(int i = 0; i < n; i++) 
     { 
      players[i] = (Player*) malloc(sizeof(Player)); 
      players[i] = new Player(); 
     } 
    } 
}Game; 

int main() 
{ 
    Game *game = new Game(10); 
    printf("%d\n", (game->players[0])->life); 
    getch(); 
    return 0; 
} 

,但它只是崩潰在運行時間,我試圖修改它,但仍然無法找出原因。

任何人都可以幫助我嗎?感謝您的回答。

(通過我使用的開發-C++的方式)

+1

您使用[保留的標識符(http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)。另外,我不知道你想在那裏與'malloc'做什麼,但它不會與'Player'工作。最簡單的辦法是隻改變'players'到'的std ::矢量'和'game'到'Game'。這些指針都不是必需的。 – chris

+0

通過您使用的是舊的IDE的方式! – haccks

+0

你混淆了C和C++:1,嘗試用C++ - 通過的iostream提供的輸入/輸出。 2.您不需要兩次分配的內存,'new'是不夠的,它會分配所需的空間爲您服務! – urzeit

回答

0

我不知道你在哪裏撿到的技術,但它是一個爛攤子。考慮以下幾點:

struct Player 
{ 
    int livesLeft; 
    Player() {livesLeft = 3;} 
} 
namespace Game 
{ 
    std::vector<Player> players; 
    bool Initialize(int numPlayers) 
    { 
      for (int i = 0; i < numPlayers; i++) 
      { 
       Player newPlayer; 
       players.push_back(newPlayer); 
      } 
    } 
} 

int main() 
{ 
    if (!Game::Initialize(10)) return 1; 
    std::cout << Game::players[0].livesLeft << std::endl; 
    std::cin.ignore(); 
    return 0; 
} 

它應該打印「3」,然後在退出之前等待輸入。