问题描述
我正在通过CS50进行工作,目前正在从事一项小型职能,以确定选举的获胜者。
void print_winner(void)
{
int max_Votes = 0;
int num_of_winners = 0;
string winners [] = {};
for (int i = 0; i < candidate_count; i++) {
//Determine if the candidate has enough Votes to be considered a winner
if (candidates[i].Votes >= max_Votes) {
//If so,increment the number of winners
num_of_winners ++;
//Assign the winning candidate to the winners array
winners[i] = candidates[i].name;
//And reset the max number of Votes required to Now be considered a winner
max_Votes = candidates[i].Votes;
}
printf("number of winners %i\n",num_of_winners);
}
for (int i = 0; i < num_of_winners; i++) {
printf("winner %s\n",winners[i]);
}
return;
}
每当我运行该函数时,计数器似乎就可以正确递增,但是在最后一次打印输出时,该数字显然是错误的:
我仍在学习C,从我读到的内容来看,这听起来像是内存分配问题或某种整数溢出问题,但是我不确定问题是什么以及如何解决它。
解决方法
您的数组获奖者的大小为0,因为您已将其初始化为:
string winners [] = {};
因此,没有有效的索引i可以让您写获胜者[i]。给您的数组适当的初始大小。另外,C语言中的“字符串”到底是什么?
,C不允许零长度数组,因此您完全依靠编译器提供的扩展名来接受该扩展名:
string winners [] = {};
但是那已经被接受了,对您没有用,因为C数组的尺寸是不可调整的。因此,任何访问数组winners
的元素的尝试都会超出其范围,从而产生不确定的行为。您所观察到的数据损坏是这种UB的常见表现之一。
通过声明数组足够大以适合您要支持的最大大小写(并通过明确拒绝较大的大小写)来解决此问题,或者通过动态为其分配内存并在需要时增加分配来解决该问题。