使用指针输入结构值时 scanf 函数中的混淆

标签 c

#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;
}

在上面的代码中我们没有使用 &pscanf函数因为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 %sint* for %d )。但在数组的情况下,指针是根据 C 标准的规则自动派生的。

也相关:http://c-faq.com/aryptr/aryvsadr.html

关于使用指针输入结构值时 scanf 函数中的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39920709/

相关文章:

c - RPI3 上 kaa C sdk 的奇怪行为

c - 为什么我使用带有 udp 套接字的 BPF 收不到任何数据包?

c - 哪种 MCU(Cortex-M) 适用于时间关键的 GPIO 应用?

c - 从树中删除节点函数在 C 中不起作用

无法针对 OCILIB 进行编译

c++ - 为什么在浮点文字的末尾添加 0 会改变它的舍入方式(可能是 GCC 错误)?

C - sysinfo() 返回错误值 i686

c++ - FFTW 性能变化

c - 如何解决 malloc() 损坏指针的情况?

c - 使用 C API 插入 SQLite 的最快方法?