To store address of a structure type variable, we can define a structure
type pointer variable as normal way. Let us consider an structure book that has
members name, page and price. It can be declared as
struct book
{
char name[10];
int page;
float price;
};
Then, we can define structure
variable and pointer variable of structure type. This can be done as
struct book b, *bptr;
Here,
b is the structure
variable and bptr is pointer variable which points address of structure
variable. It can be done as
bptr=&b;
Here, the base address of b can
assigned to bptr pointer.
An individual structure member can
be accessed in terms of its corresponding pointer variable by writing
ptr_variable->member
Here, -> is called arrow operator and there must be pointer to
the structure on the left side of this
operator.
Example:
Create a structure named book which has
name, pages and price as member variables. Read name of book, its page number
and price. Finally display these members’ value. Use pointer to structure
instead of structure itself to access member variables.
void main()
{
struct book
{
char name[20];
int pages;
float price;
};
struct book b={"Let us C",230,456.50},*ptr; // structure
initialization
ptr=&b;
clrscr();
printf("\nName=%s\tPages=%d\tPrice=%f",ptr->name,ptr->pages,ptr->price);
/* same as b.name,
b.pages and b.price */
getch();
}
Here, ptr->name refers the
content at address pointed by ptr variable.
Comments
Post a Comment