Code:
country *add_country(struct country *array, char *name)
{
int i;
for (i = 0; array.name != NULL; i++);
struct country *newcountry = realloc(array, sizeof(struct country) * (i + 2));
if (newcountry == NULL) {
return NULL; //allocating failed
}
newcountry.name = name;
newcountry.medals.gold = 0;
newcountry.medals.silver = 0;
newcountry.medals.bronze = 0;
newcountry[i + 1].name = NULL;
return newcountry;
}
void printtable(struct country *a)
{
for (int i = 0; a.name != NULL; i++) {
printf("%s %d %d %d\n", a.name, a.medals.gold, a.medals.silver,
a.medals.bronze);
}
}
int main()
{
struct country *array = malloc(sizeof(struct country));
array[0].name = NULL; //Initialize array
char input[80];
char c[20];
printf("Enter country and medals\n");
printf("\n");
while (1) {
fgets(input, sizeof(input), stdin);
if (input[0] == 'A') {
sscanf(input, "%*c %s", c);
array = add_country(array, c);
if (array == NULL) {
printf("\nCreating country failed");
}
} else if (input[0] == 'L') {
printtable(array);
} else if (input[0] == 'Q') {
free(array);
printf("Exiting program.\n");
break;
}
}
return 0;
}
I'm building a program that calculates Olympic medals for different countries. First input is for Example 'A USA' which creates a new field. Second input is for example 'L' which prints the table 'USA 0 0 0'. Problem occurs however, when I want to input a second country. For example, if my inputs where to look like this:
A USA
A CANADA
L
It should print out:
USA 0 0 0
CANADA 0 0 0
But the result i get is:
CANADA 0 0 0
CANADA 0 0 0
I suspect that the second input somehow overwrites the first input (I dunno, beginner right here...)? If someone could help me with this it would be great!