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

如何编写C程序:输入单个动物名返回对应内存地址

修正后的C程序:根据输入动物名返回对应内存地址

原程序的问题在于没有读取用户输入的内容,直接循环输出了所有动物的内存地址,完全没做匹配逻辑。以下是修正后的代码,实现了输入单个动物名称后返回对应内存地址的功能:

// 根据用户输入的动物名称,返回该动物名称对应的内存地址
#include <stdio.h>
#include <string.h> // 用于字符串比较函数strcmp

int main() {
    const char* animals[5] = {"Lion", "Tiger", "Jaguar", "Cheetah", "Puma"};
    char input[20]; // 存储用户输入的动物名称
    int i;
    int found = 0; // 标记是否找到匹配的动物

    printf("Write the name of an animal: ");
    fgets(input, sizeof(input), stdin); // 读取用户输入
    
    // 去掉fgets读取到的换行符
    input[strcspn(input, "\n")] = '\0';

    // 遍历动物数组,寻找匹配项
    for(i = 0; i < 5; ++i) {
        if(strcmp(input, animals[i]) == 0) {
            printf("The address of '%s' is: %p\n", animals[i], animals[i]);
            found = 1;
            break; // 找到匹配后退出循环
        }
    }

    // 如果没有找到匹配项,提示用户
    if(!found) {
        printf("No matching animal found.\n");
    }

    return 0;
}

关键修改说明:

  • 引入<string.h>头文件:提供字符串比较函数strcmp,用于匹配用户输入和数组中的动物名
  • 添加input字符数组:存储用户输入的内容
  • 使用fgets读取输入:相比scanf更安全,避免缓冲区溢出问题,同时处理换行符
  • 匹配逻辑:遍历数组时用strcmp比较字符串,找到匹配项后输出对应地址并终止循环
  • 无匹配处理:如果输入的动物名不在数组中,给出明确提示

内容的提问来源于stack exchange,提问作者Michel Amir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:37:11