我想填充一个我希望是“动态”的数组,以便我可以在运行时输入尽可能多的条目。然而,阵列,可我相信指针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
的原因是因为我应该在输入数组之前对输入执行有效性检查。
我很迷茫搜索答案;对于我现在的位置来说,其中的大部分过于复杂。
嗨,你把问题标记为c,但代码看起来像C++。请说清楚它是哪一个。 – MByD 2012-04-19 17:28:37
你为什么使用realloc而不是malloc? – TJD 2012-04-19 17:28:52
你不应该使用'realloc'来重新分配内存来改变大小。你应该使用'malloc'或'calloc'。 – twain249 2012-04-19 17:29:38