在使用指针输入结构值时,scanf函数出现混乱

在使用指针输入结构值时,scanf函数出现混乱,c,C,在上面的代码中,我们没有在scanf函数中使用&p,因为p本身存储a的地址,所以为什么要在结构中使用&ptr->number和&ptr->price 为什么在scanf中输入名称时只使用ptr->name 输入编号和价格&ptr->number,&ptr->price 因为ptr->name是一个数组,数组的名称在表达式中转换为指向其第一个元素的指针。因此,将其传递给scanf()时没有使用&(的地址),使用&ptr->name将是错误的。 但其他标量类型没有这种“衰减”特性。因此,使用了& 见

在上面的代码中,我们没有在
scanf
函数中使用
&p
,因为
p
本身存储
a
的地址,所以为什么要在结构中使用
&ptr->number
&ptr->price

为什么在scanf中输入名称时只使用ptr->name 输入编号和价格&ptr->number,&ptr->price

因为
ptr->name
是一个数组,数组的名称在表达式中转换为指向其第一个元素的指针。因此,将其传递给scanf()时没有使用
&
(的地址),使用
&ptr->name
将是错误的。 但其他标量类型没有这种“衰减”特性。因此,使用了
&

见: 在第二个程序中,
p
已经是一个指针。因此,传递
&p
将是
int**
,而
scanf()
要求格式说明符
%d
使用
int*

基本上,在这两种情况下,都需要传递指针(
char*
用于
%s
int*
用于
%d
)。但是对于数组,指针是根据C标准的规则自动派生的


同样相关:

具有更高优先级的&or->
->
(解除引用)绑定比
(的地址)更紧<代码>&ptr->name
等同于
&(ptr->name)
。为什么(*ptr)。数字与ptr->numberC标准定义的数字相同,它们是等效的。原因可能是历史原因,也是为了便于使用。考虑一个包含指向另一个结构的指针的结构可以写成<代码> p> > q>值< /代码>。使用
*
编写相同的代码更麻烦。
#include <stdio.h>
struct invent
{
   char name[20];
   int number;
   float price;
};

int main()
{
   char ch;
   struct invent product[3],*ptr;
   printf("INPUT\n\n");
   for(ptr=product;ptr<product+3;ptr++)
      scanf("%s %d %f",ptr->name,&ptr->number,&ptr->price);

   printf("\nOUTPUT\n\n");
   ptr=product;
   while(ptr<product+3)
   {
      printf("%20s %5d %10.2f\n",ptr->name,ptr->number,ptr->price);
      ptr++;
   }

   return 0;
}
int main()
{
    int a,*p;
    p=&a;
    scanf("%d",p);
    printf("%d",a);
    return 0;
}