user7038946 user7038946 - 24 days ago 12
C Question

Incrementing value pointed to by int* from struct*

I have a struct defined like so:

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


Allocated like so:

candidate* Person[10];
int i;
for (i = 0; i < 10; i++) {
Person[i] = malloc(sizeof(candidate));
Person[i]->name = malloc(25*sizeof(char));
Person[i]->numVotes = malloc(sizeof(int));
}


Trying to increment value stored in numVotes like so:

int v;
scanf("%d",&v);
while (v != 0) {
switch (v) {
case 1 :
Person[0]->numVotes++;
break;
case 2 :
Person[1]->numVotes++;
break;
case 3 :
Person[2]->numVotes++;
break;
case 4 :
Person[3]->numVotes++;
break;
case 5 :
Person[4]->numVotes++;
break;
case 6 :
Person[5]->numVotes++;
break;
case 7 :
Person[6]->numVotes++;
break;
case 8 :
Person[7]->numVotes++;
break;
case 9 :
Person[8]->numVotes++;
break;
case 10 :
Person[9]->numVotes++;
break;
default :
printf("Spoiled vote\n");
break;

}
scanf("%d",&v);
}


However when printing the results I believe this is incrementing the memory address pointed to by numVotes. In addition, it gives me invalid pointer when trying to free the memory. How can I increment only the value (not the memory address) pointed to by Person[i]->numVotes? Thank you.

Answer

I agree that you shouldn't use *int and you should use int . But if you must

++(*Person[2]->numVotes);
....
printf(%d, *Person[2]->numVotes);

also it seems you forgot to zero initialize you will get garbage values always so add

memset(Person[i]->numVotes , 0, sizeof (int));

in your for loop

Comments