#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;
}
为什么在 scanf
仅输入姓名的功能ptr->name
在输入数量和价格时使用 &ptr->number
, &ptr->price
用来。我想问一下为什么我们使用 &
完全是因为ptr
本身存储结构的地址。这里再用一段代码来解释
int main()
{
int a,*p;
p=&a;
scanf("%d",p);
printf("%d",a);
return 0;
}
在上面的代码中我们没有使用 &p
在 scanf
函数因为p
本身存储着a
的地址,那么为什么要使用 &ptr->number
和 &ptr->price
用于结构。
最佳答案
Why in scanf function for entering name only ptr->name is used while entering number and price &ptr->number,&ptr->price
因为 ptr->name
是一个数组,而数组的名称在表达式中被转换为指向其第一个元素的指针。因此,在将它传递给 scanf() 时没有使用 &
(地址)并且使用 &ptr->name
是错误的。
但是其他标量类型没有这种“衰减”属性。因此,使用了&
。
参见:What is array decaying?
在您的第二个程序中,p
已经是一个指针。因此,传递 &p
将是 int**
而 scanf()
需要一个 int*
作为格式说明符 %d
。
基本上,在这两种情况下,您都需要传递指针(char*
for %s
和 int*
for %d
)。但在数组的情况下,指针是根据 C 标准的规则自动派生的。
关于使用指针输入结构值时 scanf 函数中的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39920709/