函数不更新int字段

时间:2014-09-04 20:52:30

标签: c

一切似乎工作正常,除了我的SPOILED票数int保持在0并且不是由函数更新。我已经尝试添加一个指针,认为它会指向函数外部的对象,但是++函数没有更新

#include <stdio.h>

struct candidates
{
 char name[20];
 int votes;
};
struct candidates electionCandidates[7];

void Initialize(struct candidates EC[]);
void Processvotes(struct candidates EC[], int *BadVote);
void printResults(struct candidates EC[], int *BadVote);

int main()

{

    int i, SPOIL = 0;

    Initialize(electionCandidates);
    Processvotes(electionCandidates, &SPOIL);
    printResults(electionCandidates, &SPOIL);

    for(i = 0; i < 7; i++)
    {
        printf("%s",electionCandidates[i].name);
        printf("%d\n\n",electionCandidates[i].votes);
    }

    printf("%d", SPOIL);

}

void Initialize(struct candidates EC[])
{
    int i;

    FILE *fp;
    fp = fopen("elections.txt", "r");

    for (i = 0; i < 7; i++)

    {
        fgets(EC[i].name, 20, (FILE*)fp);
    }

    fclose(fp);
}


void Processvotes(struct candidates EC[], int *BadVote)
{
        int TVOTE, i;

        FILE *fp;
        fp = fopen("elections.txt", "r");

        for (i = 0; i < 7; i++)
        {
            fgets(EC[i].name, 20, (FILE*)fp);
        }

        for (i = 0; i < 365; i++)
        {
            fscanf(fp, "%d", &TVOTE);

            if (TVOTE == 1)
                EC[0].votes++;
            if (TVOTE == 2)
                EC[1].votes++;
            if (TVOTE == 3)
                EC[2].votes++;
            if (TVOTE == 4)
                EC[3].votes++;
            if (TVOTE == 5)
                EC[4].votes++;
            if (TVOTE == 6)
                EC[5].votes++;
            if (TVOTE == 7)
                EC[6].votes++;

            if (TVOTE < 1 || TVOTE > 7)
                *BadVote++;
        }

        fclose(fp);
}

void printResults(struct candidates EC[], int *BadVote)
{

    int i, Win = 0, WinSCORE = 0, Runner = 0, RunnerSCORE = 0;

    for (i = 0; i < 7; i++)
    {

        if (EC[i].votes > WinSCORE)
        {
            WinSCORE = EC[i].votes;
            Win = i;
        }

        if (EC[i].votes == WinSCORE)
        {
            RunnerSCORE = EC[i].votes;
            Runner = i;
        }
    }


    if (WinSCORE == RunnerSCORE)
    {
        printf("There was a tie between %s and %s who both got a total of %d votes each. There were %d spoiled votes\n", EC[Win].name, EC[Runner].name, WinSCORE, *BadVote);
    }

    else
        printf("%s won the election with a total of %d votes. There was a total of %d spoiled votes.\n", EC[Win].name, WinSCORE, *BadVote);


}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

后缀++运算符优先于*;当你写*BadVote++时,你实际上是在递增指针,而不是指向的值。你应该写(*BadVote)++。有关详情,请参阅this question

答案 1 :(得分:0)

我很确定这是运营商优先级的问题。试试这个:     if(TVOTE&lt; 1 || TVOTE&gt; 7)        (* BadVote)++;