STRUCTURES AND POINTERS - C-Tutorial

Latest

Thursday, 20 October 2016

STRUCTURES AND POINTERS

STRUCTURES AND POINTERS


ü  In C, the pointer is a variable that holds the address of another data variable.
ü  A pointer to structure means a pointer variable can hold the address of a structure.
ü  The address of structure variable can be obtained by using the '&' operator.
ü  All structure members inside the structure can be accessed using pointer, by assigning the structure variable address to the pointer.

Syntax :

struct structname
{
datatype  member1;
datatype  member2;
}variable1, *ptrvariable1;    

Here, ptrvariable1 can be assigned to any other structure of the same type, and can be used to access the members of its structure.

EXAMPLE PROGRAM:

In this program, “record1” is normal structure variable and “ptr” is pointer structure variable. As you know, Dot(.) operator is used to access the data using normal structure variable and arrow(->) is used to access data using pointer variable.

#include <stdio.h>
struct student
{
     int id;
     char name[30];
     float percentage;
};
main()
{
     int i;
     struct student record1 = {1, "Raju", 90.5};
     struct student *ptr;

     ptr = &record1;    

         printf("Records of STUDENT1: \n");
         printf("  Id is: %d \n", ptr->id);
         printf("  Name is: %s \n", ptr->name);
         printf("  Percentage is: %f \n\n", ptr->percentage);
         getch();

}

No comments:

Post a Comment