我正在尝试输出包含用户输入的数组的所有元素。 例如,如果用户输入形容词“微笑”、“快乐”和“悲伤”,我想将其输出回用户。
#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
和 名词
。
此外,adj
和 nouns
都是单个 char
元素的数组,即单个字符,而不是字符串。您需要将它们设为字符数组的数组(因为 C 字符串是字符数组,所以 C 字符串数组也是字符数组的数组)。
关于c - 输出数组的所有元素 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15176487/