我知道在C编程中,对于除字符串以外的所有可变类型(int,float,char,..),'scanf'与'&'一起使用。这是我的程序代码。在'scanf'前面,为什么不需要'&'?我可以进一步了解scanf吗?
#include <stdio.h>
#define M 10
int main()
{
int i, n, sum = 0;
int a[M];
do{
printf("Input a positive number less than %d \n",M);
scanf("%d", &n);
}while (!(n >0 && n < M));
printf("Input %d numbers \n",n);
for(i=0; i<n ; i++){
scanf("%d",(a+i));
sum += *(a+i);
}
printf("Sum = %d \n",sum);
}
因为您已将a
声明为array,所以使用该变量名称的表达式本身将通常衰减至pointer数组的第一个元素(What is array decaying?-但也请参见Eric Postpischil添加的出色注释,以了解例外情况)。这类似于使用char[]
字符串,正如您正确指出的那样,将&
运算符作为参数传递给scanf
时,不需要使用该运算符。
将i
添加到a
数组的此“基地址”将为地址
这里是关于pointer arithmetic in C的不错的教程,您可能会觉得有用。
在c中的变量之前使用的[&
运算符返回该变量的地址。数组的基数已经是您想要的地址。 a+i
就像您正在使用指针算术,并通过i
scanf
通常采用要读取的变量的地址。 a
已经是一个地址(一个退化为指针的数组),i
仅仅是该地址的偏移量。