【发布时间】:2021-07-11 14:02:54
【问题描述】:
根据 check50,当给定一个无效候选人的名字时,投票函数不会返回 false。此外,它会在投票给无效候选人时修改总票数。根据说明,我保持主要功能不变。请帮忙!我在这里没有看到什么?
编辑:添加了其余代码。当我以 Alice 和 Bob 作为候选人的例子运行它并尝试投票给 Steve 时,而不是输出应该是“无效投票”,它给了我“分段错误”。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner();
}
// Update vote totals given a new vote
bool vote(string name)
{
for (int i = 0; i < MAX; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
candidates[i].votes++;
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int high = 0;
for (int i = 0; i < MAX; i++)
{
if (candidates[i].votes > high)
{
high = candidates[i].votes;
}
}
for (int j = 0; j < MAX; j++)
{
if (candidates[j].votes == high)
{
printf("%s\n", candidates[j].name);
}
}
return;
}
【问题讨论】:
-
请发帖minimal reproducible example,包括您的输入和输出。单独的功能没有问题。
-
@EugeneSh。你认为是什么导致了这个分段错误?据我了解,它发生在尝试访问数组外部的内存时。我仍然不明白这是怎么发生的,因为
i在 for 循环中应该保持小于MAX -
你不应该迭代到
MAX,你应该迭代到实际的候选人数量。你迭代的任何地方。 -
所以你需要将
candidate_count传递给遍历数组的所有函数。 -
知道了,谢谢!