Pointers - 9 Pointer & Structures

Pointer & Structures :

Structures can also be operated using pointers. It can be accessed in two ways,

1. Using referencing pointer
2. using dynamic memory location

Method 1.

        In the first method we need to store the address of structure variable into pointer and each member of a structure must be accessed by writing in the following method,

                  pointer-to-structure->membername

in place of .(dot) operator we use -> operator.

Example :

# include < stdio.h >
struct student
{
char name[30];
int s1, s2, s3, total;
};

main()
{
 struct student s,*p;
p = &s;

printf ( " \n Enter the Name and Marks for Subject1, Subject2, Subject3 \n " );
scanf ("%s%d%d%d", p->name, &p->s1, &p->s2, &p->s3 );
p->total = p -> s1 + p -> s2 + p -> s3;

printf ( "\n Name=%s \n Subject1=%d \n Subject2 = %d \n Subject3 =%d\nTotal=%d",p->name,p->s1,p->s2,p->s3,
p->total);
}

Comments