如何修复数组,标识符和初始化程序错误?

谁能帮忙解决此代码?它有4个错误

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

#define MAX 9

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

candidate candidates[MAX];

int candidate_count;


bool vote(char names[]);
void winner(void);

int main(int argc, char **argv)
{
    if(argc < 2)
    {
        printf("Usage: Plurality [Cnadidate...]\n");
        return 1;
    }
    candidate_count = argc - 1;
    if(candidate_count > MAX)
    {
        printf("The maximum number of candidates are %d\n", MAX);
        return 2;
    }
    //
    for(int i = 0; i < candidate_count; i++)
    {
        candidates[i].names = argv[i + 1];
        candidates[i].votes = 0;
    }
     int voter_count;
     printf("Enter the number of voters: \n");
     scanf("%d", &voter_count);

     for(int j = 0; j < voter_count; j++)
     {
         printf("Vote: \n");
         scanf("%s", names[j]);
     }
     if(!vote(names))
     {
         printf("Invalid");
     }

     winner();
}

bool vote(char name[])
{
    bool exist = false;

    for (int i = 0; i < candidate_count; i++)
    {
        //check if the typed in name is in the list of candidates
        if (strcmp(name, candidates[i].names) == 0)
        {
            candidates[i].votes ++;
            exist = true;
            break;
        }

    }

    return exist;
}

void winner(void)
{
    int most = candidates[0].votes;
    char winner[10] = candidates[0].names;
    for (int i = 1; i < candidate_count; i++)
    {
        if (most < candidates[i].votes)
        {
            most = candidates[i].votes;
            winner = candidates[i].names;
        }
    }

    //printf("%d", most);
    printf("%s\n", winner);
    return;
}

错误:

plurality.c:39:29: error: array type 'char [10]' is not assignable
        candidates[i].names = argv[i + 1];
        ~~~~~~~ ^
plurality.c:49:22: error: use of undeclared identifier 'names'
         scanf("%s", names[j]);
                     ^
plurality.c:51:15: error: use of undeclared identifier 'names'
     if(!vote(names))
             ^
plurality.c:81:10: error: array initializer must be an initializer list or string literal
    char winner[10] = candidates[0].names;
         ^
4 errors generated.
评论
  • aeius
    aeius 回复

    You can't assign arrays in C or C++, for arrays representing C strings you can use the function strcpy instead

    strcpy(candidates[i].names, argv[i + 1]);
    

    strcpy(winner, candidates[i].names);