Structure and Pointer

In this tutorial, you will learn to access structures elements by using the structure pointer. As we have created the pointer variable of integer, float or any other common data types. similarly, we can also create the pointer for structure variable and such pointers are the structure pointer. We will use a special operator for accessing the data of structure. We will use the arrow operator to access structure members. Below, you will see the syntax of the structure and pointer which will make you understand more about it.

Syntax:

structure variable -> structure element

Now, look at the example below. This is a simple example which defines a book. The book will consist of page and price as elements. Here,  we will be writing a program implementing pointer and structure. That will accept the information of two blocks and display it using the structure pointer.

Code:

#include<stdio.h>
struct Book
    {
		int page;
		double price;
	};
	
int main()
{
	struct Book *bookPtr, book1;
    bookPtr = &book1;   

    printf("Enter the page: ");
    scanf("%d", &bookPtr -> page);

    printf("Enter the price:");
    scanf("%ld", &bookPtr -> price);

    printf("Displaying:\n");
    printf("The page entered is %d\n", bookPtr -> page);
    printf("The price entered is %ld", bookPtr -> price);

    return 0;
	
}

The above program will display its output as below.

Output:

Enter the page: 1550
Enter the price:200
Displaying:
The page entered is 1550
The price entered is 200

 

 

SHARE Structure and Pointer

You may also like...

Leave a Reply

Your email address will not be published.

Share