为什么在下面的代码中不需要与号?

问题描述 投票:3回答:3

我知道在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);
}
c pointers scanf
3个回答
3
投票

因为您已将a声明为array,所以使用该变量名称的表达式本身将通常衰减至pointer数组的第一个元素(What is array decaying?-但也请参见Eric Postpischil添加的出色注释,以了解例外情况)。这类似于使用char[]字符串,正如您正确指出的那样,将&运算符作为参数传递给scanf时,不需要使用该运算符。

i添加到a数组的此“基地址”将为地址

(即指向[指针)数组的第i个元素。

这里是关于pointer arithmetic in C的不错的教程,您可能会觉得有用。


1
投票

在c中的变量之前使用的[&运算符返回该变量的地址。数组的基数已经是您想要的地址。 a+i就像您正在使用指针算术,并通过i


1
投票

scanf通常采用要读取的变量的地址。 a已经是一个地址(一个退化为指针的数组),i仅仅是该地址的偏移量。

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