首页 > 解决方案 > 与 **characters** VS 与 **integers** 一起使用时,数组作为参数

问题描述

我遇到了一个矛盾 - 在我看来 - 当使用数组作为函数中的参数时scanf(),字符和整数。在 Deitel 和 Deitel 书中,我正在研究字符处理库,它介绍了当 - 例如 - 分配:"char word[ 20 ]"然后"scanf( "%s", word );",这里的scanf()函数不需要&运算符。但是在分配时:"int array[ 10 ]"然后在扫描用户的输入时,这里需要&操作员!有人可以为我解释一下吗?

标签: carraysstringcharacterscanf

解决方案


char word[20];
scanf("%s", word);

它将读取用户输入的整个字符串(字符集合)word。因此,如果我输入“Hi”,那么word[0]将会是'H'并且word[1]将会是'i'

int array[10];
scanf("%d", &array[0]); // Stores the number the user typed into 'array[0]'
scanf("%d", &array[1]); // Stores the number the user typed into 'array[1]'

这里我们使用&,但我们也访问数组的一个元素,因为格式说明符%d是一个数字。

为了得到类比,请考虑以下示例:

char word[20];
scanf("%c", &word[0]);
scanf("%c", &word[1]);

这里的格式说明符是要求一个字符(而不是字符集合(即字符串))。


推荐阅读