c - 输出数组的所有元素 - C

标签 c for-loop

我正在尝试输出包含用户输入的数组的所有元素。 例如,如果用户输入形容词“微笑”、“快乐”和“悲伤”,我想将其输出回用户。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int counter_1, counter_2, counter_3, tracker;

    printf("Enter a number of adjectives: ");
    int numAdj;

    scanf("%d", &numAdj);

    printf("Enter a number of nouns: ");
    int numNouns;

    scanf("%d", &numNouns);

    char adj[numAdj];
    char nouns[numNouns];

    printf("Please enter %d adjectives: \n", numAdj);

    for (counter_1 = 0; counter_1 <= numAdj - 1; counter_1++) {
        scanf("%s", &adj[counter_1]);
    }

    printf("Please enter %d nouns: \n", numNouns);

    for (counter_2 = 0; counter_2 <= numNouns - 1; counter_2++) {
        scanf("%s", &nouns[counter_2]);
    }

    for (counter_3 = 0; counter_3 <= numAdj - 1; counter_3++) {
        printf("%s", &adj[counter_3]);
    }
    return 0;
}

我不明白为什么我无法输出数组的数据。

最佳答案

您正在从数组 adj 进行打印,该数组只有 numAdj 元素的空间,即,如果 numAdj 为 3,您只能访问元素 adj[0]adj[1]adj[2]。然而,最后的循环迭代到 numAdj * numNouns,只要 numNouns 不为 0(在这种情况下,它只打印第一个元素 adj[0])。

使用前两个循环中的 for 行来正确迭代 adj名词

此外,adjnouns 都是单个 char 元素的数组,即单个字符,而不是字符串。您需要将它们设为字符数组的数组(因为 C 字符串是字符数组,所以 C 字符串数组也是字符数组的数组)。

关于c - 输出数组的所有元素 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15176487/

相关文章:

c++ - 对于一个参数

python - for 循环 & if 在字典中

c++ - 通过c/c++程序在linux中生成系统声音

c - #pragma 指令编译器依赖吗?

programming-languages - 为什么某些编程语言会限制您编辑正在循环的数组?

swift - 在 for 循环中更改 SKNode 子节点的属性

javascript - 如何用下划线替换数组中的某些字母

android - 如何从 unsigned char* 数组中获取 jpeg 图像数组?

c - 从另一个函数返回一个函数指针

python - C 和 Python 中的套接字