Имя и код жирафа должны быть изменены пользователем после однократной печати.Я ввожу разные значения для каждого из них, но «код» совпадает с «именем».
Мне кажется, я знаю, как обойти эту ошибку, но я бы хотел знать, как решить эту проблему, не внося слишком много изменений или дополнений в мой код.Я полагаю, что я использую указатели, так как я впервые с ними общаюсь.
Взгляните:
typedef struct {
int age;
double height;
char *name;
}giraffe;
void renameGiraffe(giraffe *g, char *na){
g->name = na;
}
void recodeGiraffe(char * codes[], int n, char * code){
codes[n] = code;
}
int main()
{
giraffe north; giraffe south; giraffe west;
north.name = "Fred";
south.name = "Bill";
west.name = "Kate";
char in1[] = "";
giraffe* exhibit[] = {&north, &south, &west};
char* codes[] = {"GN","GS","GW"};
for(int i = 0; i < (sizeof(exhibit)/sizeof(exhibit[0])); i++)
{
printf("The giraffe named %s has the code %s\n", exhibit[i]->name, codes[i]);
}
printf("Let's recode a giraffe. Which giraffe would you like to recode?\n\n");
scanf("%s", in1);
if(strcmp("north", in1)== 0)
{
printf("what is the new code for north?\n");
scanf("%s", in1);
recodeGiraffe(codes, 0, in1);
printf("North has been recoded. The new code for north is %s\n", in1);
}
printf("Let's rename the north giraffe. What's the new name?\n");
scanf("%s",in1);
renameGiraffe(&north, in1);
printf("Reprinting the list of giraffes now:\n\n");
for(int i = 0; i < (sizeof(exhibit)/sizeof(exhibit[0])); i++)
{
printf("The giraffe named %s has the code %s\n", exhibit[i]->name, codes[i]);
}
return 0;
}
Мой вывод:
The giraffe named Fred has the code GN // Ignore the other two giraffes.
The giraffe named Bill has the code GS
The giraffe named Kate has the code GW
Let's recode a giraffe. Which giraffe would you like to recode?
north
What is the new code for north?
NOR
North has been recoded. The new code for north is NOR
Let's rename the north giraffe. What's the new name?
FREDDY
Reprinting the list of giraffes now:
The giraffe named FREDDY has the code FREDDY //The code should be NOR.
The giraffe named Bill has the code GS
The giraffe named Kate has the code GW