Structures and pointers - How pointers related to structures in C

By
Advertisement
Structures and Pointers : Structure can be directly handle by its address by using the pointer with structure. We use pointer with structure through structure variable. The beginning address of the structure can be accessed in the same manner as any other address. Through the use of address operators (&). The general syntax used for the declaration of pointer with the structure is as

Struct tag_name
{
Type 1 member 1;
type2 member2;
.
.
.
typeN memberN;
};
Struct tag_name v, *p;
Where ‘v’ is the structure variable and ‘p’ is the pointer variable.
Ex : structure employee
{
int no;
char name [10];
float sa;
};
struct employee emp,*p;

An individual structure member can be accessed in terms of its corresponding pointer variable by writing.
P->member
Where ‘p’ refer to a structure type pointer variable and the operator(->)

Here is the example program how to declare a structure variable as pointer and how to access it.
Struct student
    {
    Int no;
    Char name [10]
    Int m1;
    Int m2;
    Int m3;
    };
    void main()
    {
        struct student std;
        struct student*p;
        p=&std;
        clarscr();
        printf (“enter student number”);
        scanf(“%d”,&p->no);
        printf(Enter student name”);
        scanf(“%s”, p-name”);
        printf(“Enter marks in 3 subjects”);
        scanf(“%d%d%d”,&p->m1, &p->m2,&p->m3);
        printf(“Student number=%d”,p->no);
        printf(“student name=%s”,p->name);
        printf(“\n marks in m1=%d”,p->m1);
        printf(“\n marks in m2=%d”,p->m2);
        printf(“\n marks in m3=%d”,p->m3);
        getch();
    }
   

Output:
    Enter student number 1
    Enter student name Rohith
    Enter marks in 3 subjects 60  70  80
    Student number = 1
    Student name = Rohith
    Marks in M1 = 60
    Marks in M2 = 70
    Marks in M3 = 80







0 comments:

Post a Comment