Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion in scanf function while entering values for structure using pointer

Tags:

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

Why in scanf function for entering name only ptr->name is used while entering number and price &ptr->number, &ptr->price is used. I want to ask why we are using & at all because ptr is itself storing the address of structure. Here is another code to explain

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

In the above code we are not using &p in scanf function because p is itself storing the address of a, so why use &ptr->number and &ptr->price for structures.

like image 752
Rajesh Shaw Avatar asked Jul 02 '26 23:07

Rajesh Shaw


1 Answers

Why in scanf function for entering name only ptr->name is used while entering number and price &ptr->number,&ptr->price

Because ptr->name is an array and an array's name, in an expression, gets converted into a pointer to its first element. Hence, there's no & (address-of) used when passing it to scanf() and using &ptr->name would be wrong. But other scalar types don't have such "decaying" property. Hence, & is used.

See: What is array decaying? In your second program, p is already a pointer. So, passing &p would be int** whereas scanf() expects an int* for the format specifier %d.

Basically, in both cases you are required to pass pointers (char* for %s and int* for %d). But in the case of arrays, the pointer is automagically derived as per the rules of the C standard.

Also relevant: http://c-faq.com/aryptr/aryvsadr.html

like image 155
P.P Avatar answered Jul 05 '26 16:07

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!