0

I'm working on Plurality of pset3. I've run into an issue modifying the vote count of each candidate. I've isolated the problem in the full program below. It appears that

candidate zero = candidates[0];
zero.votes = 100;

does not change the vote count of the candidate at index 0, but

candidates[1].votes = 20;

changes the vote count of the candidate at index 1. What's the difference?

#include <stdio.h>
#include <cs50.h>

#define MAX 3

typedef struct
{
    string name;
    int votes;
}
candidate;
candidate candidates[MAX];

int main(void)
{
    string names[] =  {"kevin","bob","stuart"};

    for(int i = 0; i < MAX; i++){
        candidates[i].name = names[i];
        candidates[i].votes = 0;
    }
    candidate zero = candidates[0];
    zero.votes = 100;

    candidates[1].votes = 20;
    for(int i = 0; i < MAX; i++){
        candidate c = candidates[i];
        printf("c.name: %s c.votes: %i\n",c.name,c.votes);
    }

}

Output:
c.name: kevin c.votes: 0
c.name: bob c.votes :20
c.name: stuart c.votes: 0

Thanks for taking a look at this!

1
candidate zero = candidates[0];

creates a new variable of type candidate and copies over the value from candidates[0]. The new variable gets its initial value from candidates[0], but is not connected in any other way.

zero.votes = 100;

then sets that copy's votes to 100.

If you wanted to have different variables refer to the same actual storage, you would have to use pointers, which are explained in week 4. Basically, they store a memory location, and you can refer to the value stored in that location. And a copy of a pointer will still point to the same location.

You must log in to answer this question.

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