0

I am doing the 2020 version of CS50's pset3 and I am already stuck (again) at the runoff voter function. My code below resulted in segmentation fault. I don't know how to fix this though.

So here's my code (Let me know if this is not enough info, I only showed my code so far as the whole code is very long):

bool vote(int voter, int rank, string name)
{
    // TODO
    // Assume that the name is not yet given and update if a name is given
    bool name_exist = false;

    //Look for a candidate called name
    for (int i = 0; i <= candidate_count ; i++)
    {
        //If the input matches a candidate list update the preference
        {
            for (int j = 0; j < i ; j++)
            {
                if (strcmp(candidates[i].name, name) == 0)
                {
                    preferences[voter][rank] = candidate_count;
                    printf("%s\n",name);
                }

            }
            name_exist = true;
        }
    }
    return name_exist;

Anybody can provide some idea or suggestions? Thanks.

1

Perhaps having nested loops works, but I did not have a nested loop for the vote function. I also did not have preferences[voter][rank] = candidate_count. Candidate_count is a fixed number (once the user inputs the number). You want to update the preference, so what kind of variable could you use in place of candidate_count?

3
  • Er, not quite sure I got what you mean. I tried candidates[i].votes and it still doesn't work – user71812 Jan 18 '20 at 6:37
  • This for (int i = 0; i <= candidate_count ; i++) is the root of the segmentation fault. Remember, loop starts at 0, so this will iterate beyond the end of candidates array. Once that is fixed, this answer should become clearer. – DinoCoderSaurus Jan 18 '20 at 11:24
  • Hopefully this will clarify: preferences[voter][rank] = ? Say you're at i = 2, and indeed candidates[2].name does exist. Voter number X has put this person's name as their Yth rank. How do we update Voter X's Yth preference? With the number of this candidate (in this case, 2). Plug those numbers and letters in: preferences[voter(X)][rank(Y)] = 2. Right now, as you've put it, if there are, say, 5 candidates, preferences[voter][rank] would always equal 5. – azb1297 Jan 18 '20 at 17:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .