如何创建一个 C 程序来存储 5 种动物的名称并在用户选择其中任何一个时打印内存地址?

问题描述 投票:0回答:1
//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 个名称的地址。

arrays c pointers
1个回答
0
投票

您的程序真正需要的只是一个

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[20] = { 0 };

    int i;

    printf("Write the name of an animal: ");
    scanf("%19s", 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;
}

我冒昧地扩展了你的 printf 以包含所选动物的名称。不只是地址。

© www.soinside.com 2019 - 2024. All rights reserved.