Search Result
Details here...

Structure and Pointers

Previous

Introduction to Structure


In this tutorial, we will learn about the structure combined with pointer. But before that, make sure you know about pointers and structures.

Sometimes, it will be useful to use pointers to access the members of a structure. It happens when we want to change the value of a member of a structure variable.

Pointer to Structure

The syntax for declaring a pointer to a structure is as follows:
struct structure_name *pointer_name;
For example, we can declare a pointer ptr to a structure height as follows:
struct height {
int feet;
int inch;
};
int main() {
struct height *ptr;

.
.
.

}
The type of the pointer is struct height *.

The Arrow Operator (->)

The -> operator is used to access the members of a structure using pointers. For example, if we have a pointer ptr to a structure height, we can access the members of the structure according to the following example:
struct height {
int feet;
int inch;
};
int main() {
struct height *ptr = &height;
ptr->feet = 5;
ptr->inch = 10;

.
.
.

}

Let's have a look at an example

C

#include <stdio.h>
typedef struct height {
int feet;
int inch;
} height;

int main()
{
height my_height;
height* ptr = &my_height;
printf("Enter the height in feet and inch: ");
scanf("%d %d", &ptr->feet, &ptr->inch);
printf("The height is %d feet and %d inch", ptr->feet, ptr->inch);
return 0;
}

Output

Enter the height in feet and inch: 5
8
The height is 5 feet and 8 inch

Explanation

In the above example, a new structure height is defined. The height structure contains two members, feet and inch.

We also defined a my_height variable of type height. The variable ptr is a pointer to the my_height variable.

Moreover, we used the scanf function to read the values of feet and inch from the user. The values are stored in the my_height variable, using the arrow operator (->) and pointer to the feet and inch members of the height structure.
By darpan.kattel
Previous

Introduction to Structure