首页 > 解决方案 > 如何修复数组、标识符和初始化程序错误?

问题描述

任何人都可以帮助修复此代码吗?它有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.

标签: c

解决方案


你的代码难以理解,例如你在这部分做什么?在这种情况下,您在哪里声明了“名称”?!

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

推荐阅读