I’m trying to get a few(3 for now) names as the candidates for a vote and assign them to typedef instances with the array I have defined. But when I run the code only the last name gets saved in the array as you can see in the second loop only the last input gets printed out. Can someone please let me know what I’m doing wrong here?
My code is:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct
- {
- char *name;
- int votes;
- }
- candidate;
- #define MAX 9
- candidate candidates[MAX];
- int main(void)
- {
- char candid[10];
- for (int i =0; i<3; i++)
-
{
- scanf(“%s”,candid);
- candidates[i].name = candid;
- candidates[i].votes = 0;
-
}
- printf(“Names: n”);
- for (int i = 0; i < 3; i++)
-
{
- printf(“%sn”,candidates[i].name);
-
}
- }
Output:
Charlie
Ana
David
Names:
David
David
David
New contributor
user25196722 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.