简体   繁体   中英

Segmentation fault with bool - CS50 plurality

I am working on cs50 plurality problem. When I try to vote for a candidate that wasn't in my argv I expected "Invalid vote.\n" to be printed however my program ends in Sementation fault. Could anyone explain why? I think my logic for my bool vote may be flawed but I am not sure. Thank you!

#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)
        {
            return true;
            
        }
    }
    return false;
    
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    return;
}

....................................... ....................................... ....................................... ...................................

In function vote() the loop

for (int i = 0; i < MAX; i++)

is checking every record's string, including those with a NULL pointer.
You should use candidate_count the number of elements set.

for (int i = 0; i < candidate_count; i++)

It only goes wrong when a match for a name is not found, because the loop index only then exceeds the number of names recorded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM