My code seems to function properly until I try to exit main. At this point it reports a segmentation fault. This only occurs when there is a tie.
Here is my code:
#include <stdio.h>
#include <cs50.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;
int voter_count;
// Other global variables
int v;
// 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;
}
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 and update vote count
if (!vote(name))
{
printf("Invalid vote.\n");
}
else if (vote(name))
{
candidates[v].votes = candidates[v].votes + 1;
}
}
// Display winner of election
print_winner();
// with or without this 'return 0;' there is a segmentation fault
return 0;
}
// Update vote totals given a new vote
bool vote(string name)
{
// checks if the vote is valid
for (v = 0; v < candidate_count; v++)
{
if (strcmp(name, candidates[v].name) == 0)
{
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int top[] = {};
int num = 0;
int big = 0;
//finds the largest number
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > big)
{
big = candidates[i].votes;
}
}
// checks if there are multiple winners, populates a new array with the locations of the winners, and counts the number of winners.
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes == big)
{
top[num] = i;
num += 1;
}
}
// prints the winner(s) names
for (int i = 0; i < num; i++)
{
printf("%s\n", candidates[top[i]].name);
}
return;
}
I am also getting these errors when I run check50:
:( vote produces correct counts when all votes are zero
vote function did not correctly update vote totals
:( vote produces correct counts after some have already voted
vote function did not correctly update vote totals
Does anyone know what the problem is?