You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言练习求助:Animal结构体数组无法正确存储循环输入的数据

问题分析与修复方案

问题根源

你的代码中,循环调用getAnimal和visitAnimal时,始终传递的是结构体数组的首地址(type),导致所有输入都被写入数组的第一个元素,后续输入会覆盖之前的内容;输出时也一直读取第一个元素,所以最终重复显示最后一次输入的数据。

修复方法

修改main函数中的两个循环,传递数组中对应索引的元素地址(&type[i] 或 type+i),这样每次循环会操作数组的不同位置:

修复后的完整代码

#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 10

typedef struct {
    char name[MAX_LEN];
    char food[MAX_LEN];
    char sound[MAX_LEN];
} Animal;

void getAnimal(Animal* type);
void visitAnimal(Animal* type);

int main() {
    int i = 0;
    int count = 0;
    Animal type[MAX_LEN] = {};

    printf("How many Animals Are there on the farm?: ");
    scanf("%d", &count);

    for (i = 0; i < count; ++i) {
        // 传递第i个元素的地址,而非数组首地址
        getAnimal(&type[i]);
    }

    printf("Welcome to our farm.\n");

    for (i = 0; i < count; ++i) {
        // 同样传递第i个元素的地址
        visitAnimal(&type[i]);
    }
    return 0;
}

void getAnimal(Animal* type) {
    printf("Enter the name of the animal: ");
    scanf("%s", type->name);

    printf("What does a %s eat?: ", type->name);
    scanf("%s", type->food);

    printf("Enter the sound made by a %s: ", type->name);
    scanf("%s", type->sound);
}

void visitAnimal(Animal* type) {
    printf("This is a %s. It eats %s and says %s\n", type->name, type->food,
           type->sound);
}

关键修改点

  • 第一个循环中,将getAnimal(type)改为getAnimal(&type[i]),让每次输入的信息存入数组的第i个结构体。
  • 第二个循环中,将visitAnimal(type)改为visitAnimal(&type[i]),依次读取数组中每个位置的结构体数据。

测试验证

运行修复后的代码,输入2个动物信息后,会正确输出两个不同的动物数据:

sh-4.2$ gcc -ansi -Wall PE10.c
sh-4.2$ a.out
How many Animals Are there on the farm?: 2
Enter the name of the animal: cow 
What does a cow eat?: wheat
Enter the sound made by a cow: moo
Enter the name of the animal: Duck 
What does a Duck eat?: seeds
Enter the sound made by a Duck: quack
Welcome to our farm.
This is a cow. It eats wheat and says moo
This is a Duck. It eats seeds and says quack

内容的提问来源于stack exchange,提问作者Tyler Reed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 13:05:30