Page 13 - Sample_test_Float
P. 13

Functions and Pointers  13


              5.2.10. Pointer to Structure
              A pointer which is pointing to a structure is known as Pointer to Structure.
              Structure’s member can be accessed through pointer.

              Consider an example to access structure’s member through pointer.



               Example 1
               Using dot(.) operator:

               #include <stdio.h>
               struct book
               {
                  int pages;
                  float price;
               };
               void main()
               {
                  struct book *ptr;
                  struct book p;
                  ptr=&p;/* Referencing pointer to memory address of p */
                  printf(“Enter no of pages: “);
                  scanf(“%d”,&(*ptr).pages); // (*ptr).pages is equivalent to p.pages
                  printf(“Enter price: “);
                  scanf(“%f”,&(*ptr).price); // (*ptr).price is equivalent to p.price
                  printf(“/nDisplaying:/n “);
                  printf(“%d%f”,(*ptr).pages,(*ptr).price);
               }
               Output:

               Enter no of pages:450
               Enter price: 220.75
               Displaying:
               450 220.75




              In this example, the pointer variable of type struct is referenced to the address of p. Then the structure member
              is accessed through pointer using dot operator.
              Structure pointer member can also be accessed using -> operator.

                 (*ptr).a is same as ptr->a
                 (*ptr).b is same as ptr->b
              -> and(*).Bothrepresent the same but → operator will not have ‘*’ in front.
              These operators are also used to access data member of structure by using structure’s pointer.
   8   9   10   11   12   13   14   15   16   17