//The following program obtains the memory address of one of the 5 animal names entered by the user.

#include <stdio.h>
int main() {
    const char* x[5]={"Lion","Tiger","Jaguar","Cheetah","Puma"};

    //It is clear that &x[0]is equivalent toX. And, x[0]is equivalent to *x.

    int i; //Basically, &x[i]is equivalent to x+i and x[i]is equivalent to *(x+i).
    int *p;


    printf("Write the name of an animal: "); 
    for(i = 0; i < 5; ++i) {
        printf("The address of the chosen animal is:[%d] = %p\n", i, x[i]);
    }
    return 0;
}

这就是我所拥有的,除了我需要程序询问一只动物的名字,这样它才能给出它的记忆地址,因为程序问我动物的名字,但无论我写什么,它都会立即生成5个名字的地址.

推荐答案

您的程序真正需要做的就是调用scanf来读取用户的输入.然后使用strcmp将用户键入的字符串与x数组中的字符串进行比较.

#include <stdio.h>
#include <string.h>         // add this include for strcmp

int main() {
    const char* x[5] = { "Lion","Tiger","Jaguar","Cheetah","Puma" };

    char inputArray[21]; // 20 + 1 for null char

    int i;

    printf("Write the name of an animal: ");
    scanf("%20s", inputArray);

    for (i = 0; i < 5; ++i) {
        if (strcmp(inputArray, x[i]) == 0) {
            printf("The address of the chosen animal is:[%d] = %p. The animal chosen was %s\n", i, x[i], x[i]);
        }
    }
    return 0;
}

我冒昧地扩展了您的打印格式,包括所选动物的名称.不仅仅是地址.

p变量根本没有被使用,所以我删除了它.

strcmp调用将比较用户输入的内容(直到尾部的所有字符与x[i]中的字符,直到两者中的字符都为空.如果没有发现差异,则strcMP将返回0.

如果您希望支持不区分大小写的比较,以支持用户输入LIONlion并仍然匹配Lion,这是我留给您的一个练习.

C++相关问答推荐

初始化char数组-用于初始化数组的字符串是否除了存储数组的位置之外单独存储在内存中

为什么listen()(在调用accept()之前)足以让应用程序完成3次握手?

以c格式打印时间戳

是否有任何情况(特定类型/值),类型双关在所有符合标准的C实现中产生相同的行为?

Mise()在虚拟内存中做什么?

字符串令牌化xpath表达式

如何将已分配的数组(运行时已知的大小)放入 struct 中?

从组播组地址了解收到的数据包长度

Win32API Wizzard97 PropSheet_SetWizButton不工作

ATmega328P EEPROM未写入

拥有3x3二维数组并访问数组[1][3]等同于数组[2][0]?

在 struct 中强制转换空指针

平均程序编译,但结果不好

防止C++中递归函数使用堆栈内存

使用nmake for程序比Hello World稍微复杂一些

合并对 struct 数组进行排序

哪个首选包含第三个库S头文件?#INCLUDE;文件名或#INCLUDE<;文件名&>?

关于不同C编译器中的__attribute__支持

从系统派生线程调用CRT

是否可以在多字 C 类型中的任何位置混合存储和类型限定符?