2012-04-19 20 views
1

我想填充一个我希望是“动态”的数组,以便我可以在运行时输入尽可能多的条目。然而,阵列,可我相信指针NthTeam指向,不填充:如何让这个数组填充我的输入值?

int* NthTeam = NULL;  

NthTeam = (int*)realloc(NthTeam,(playerCounter*STND_NO_GAMES)*sizeof(int)); 

// loops through each player's standard number of games 
for (int i = 1; i <= STND_NO_GAMES; i++) { 
    //input the score into the remalloced array 
    cout << "Enter player " << playerCounter << "'s score " << i << ": "; 
    cin >> inputValue; 
    NthTeam[((playerCounter-1)*STND_NO_GAMES+(i-1)))] = SanityCheck(inputValue); 
} 

然而,当我在我的代码使用cin >> NthTeam[(playerCounter - 1) * STND_NO_GAMES + (i - 1)],它的工作...数组填充。

我被带领从this link相信你可以像使用常规数组那样使用NthTeam,但我不认为这就是发生在这里的事情。我不能仅仅使用cin的原因是因为我应该在输入数组之前对输入执行有效性检查。

我很迷茫搜索答案;对于我现在的位置来说,其中的大部分过于复杂。

+0

嗨,你把问题标记为c,但代码看起来像C++。请说清楚它是哪一个。 – MByD 2012-04-19 17:28:37

+0

你为什么使用realloc而不是malloc? – TJD 2012-04-19 17:28:52

+0

你不应该使用'realloc'来重新分配内存来改变大小。你应该使用'malloc'或'calloc'。 – twain249 2012-04-19 17:29:38

回答

0

假设您使用C++进行编程,那么标准库可以帮助您。例如:std::vector。这里有一个死脑筋的修改,并且一定要#include <vector>

std::vector<int> NthTeam;  

// loop through each player's standard number of games 
// inputting the score into the vector 

for (int i = 1; i <= STND_NO_GAMES; i++) { 
    cout << "Enter player " << playerCounter << "'s score " << i << ": "; 
    cin >> inputValue; 
    NthTeam.push_back(SanityCheck(inputValue)); 
} 

你需要考虑输入无效输入时会发生什么(就像进入了得分“番茄”的)。考虑这将如何影响cin的错误状态,当最后一次尝试产生错误时尝试读取其中的另一个整数以及inputValue将如何处理时,它会执行什么操作。

可能出现这种情况,您仍然需要一个“SanityCheck”......但它可以理所当然地认为它只需要检查整数。