ccommand-line-argumentstypedef

Can't save names in typedef instances


I'm trying to create a voting project in c where you get the candidates names in command line and then the voters number and votes. The function bool vote(char name[]) counts the votess and the void print_winner(void) prints the winner. The problem is that I can't save candidates name in the typedef name instance because when the votes are entered it keeps printing "Invalid name" meaning the candidate name doesn't exist.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

bool vote(char name[]);
void print_winner(void);
#define MAX 9
int candidate_count;

typedef struct
{
    char *name;
    int votes;
}
candidate;

candidate candidates[MAX];
int main(int argc, char *argv[])
{
    int voter_count;
    char cast[10];
    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;
    }

    printf("Number of voters: ");
    scanf("%i",&voter_count);

    for (int i=0; i<voter_count; i++)
    {
        printf("Vote: ");
        scanf("%s",cast);

        if(!vote(cast))
        {
            printf("Invalid vote\n");
        }
    }
    print_winner();

}

bool vote(char name[])
{
    for (int j=0; j<candidate_count; j++)
    {
        if(strcmp(name,candidates[j].name)==0)
        {
            candidates[j].votes++;
            return true;
        }
        
    }

    return false;
    
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    int largest = candidates[0].votes;

    for(int i=0; i<candidate_count; i++)
    {
        if(candidates[i].votes>largest)
        {
            largest=candidates[i].votes;
        }
    }
    for(int i=0; i<candidate_count;i++)
    {
        if(largest==candidates[i].votes)
        {
            printf("winner is %s",candidates[i].name);
        }
    }

    return;
    
}

Running: gcc plurality.c -o out
./out John charlie David

Output:
Number of voters: 3
Vote: David
Invalid vote
Vote: charlie
Invalid vote
Vote: David 
Invalid vote

When I change the typedef's instance to

typedef struct
 {
 char name[10];
 int votes;
 }
 candidate;

I get the "assignment to expression with array type" error


Solution

  • At least this issue:

    int candidate_count; in main() shadows the global int candidate_count; which remains with the value of 0. The loop in vote() iterates 0 times.

    Delete int candidate_count; in main() so candidate_count = argc - 1; sets the global candidate_count.