Wednesday 31 May 2017

Pointer to Structure in C ~ GNIITHELP

Pointer to Structure

Like we have array of integers, array of pointer etc, we can also have array of structure variables. And to make the use of array of structure variables efficient, we use pointers of structure type. We can also have pointer to a single structure variable, but it is mostly used with array of structure variables.
struct Book
{
 char name[10];
 int price;
}

int main()
{
 struct Book a;       //Single structure variable
 struct Book* ptr;    //Pointer of Structure type
 ptr = &a;
 
 struct Book b[10];     //Array of structure variables
 struct Book* p;        //Pointer of Structure type
 p = &b;    
}

Pointer to Structures

Accessing Structure Members with Pointer

To access members of structure with structure variable, we used the dot . operator. But when we have a pointer of structure type, we use arrow -> to access structure members.
struct Book
{
 char name[10];
 int price;
}

int main()
{
 struct Book b;
 struct Book* ptr = &b;   
 ptr->name = "Dan Brown";      //Accessing Structure Members
 ptr->price = 500;
}

No comments:

Post a Comment