【发布时间】:2012-04-19 17:26:22
【问题描述】:
我正在尝试填充一个我希望是“动态”的数组,以便我可以在运行时根据需要向其中输入尽可能多的条目。但是,我认为指针 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++。请说清楚是哪一个。
-
你为什么使用 realloc 而不是 malloc?
-
您不应该使用
realloc来重新分配内存以更改大小。您应该使用malloc或calloc。 -
这是在
do...while循环的中间,我摘录了代码。playerCounter不断迭代。 -
当然,在 C++ 中,您根本不应该使用
malloc、realloc等。我真诚地希望你的班级没有教你。你最好使用标准容器,例如vector。