Pointer to structures
C program to show the usage of pointer to structures.
Program
#include<stdio.h>
#include<conio.h>
struct person
{
char name[20];
int age;
float weight;
};
void main()
{
struct person p1;
struct person *ptr;
ptr = &p1;
printf("Enter name\t:");
scanf("%s",ptr->name);
printf("Enter age\t:");
scanf("%d",&ptr->age);
printf("Enter weight\t:");
scanf("%f",&ptr->weight);
printf("\n\nEntered data is");
printf("\nName\t:%s",ptr->name);
printf("\nAge\t:%d",ptr->age);
printf("\nWeight\t:%f",ptr->weight);
getch();
}
Output
Enter name :Aman
Enter age :30
Enter weight :93.8
Entered data is
Name :Aman
Age :30
Weight :93.800000
Explanation
In the above program, a structure 'person' is defined and a variable 'p1' of struct person type is declared. A struct pointer 'ptr' is also declared. The starting address of 'p1' is stored in the 'ptr' pointer using
Now, you can access the members of 'p1' using the 'ptr' pointer. To access members of structure using the structure variable, we used the dot (.) operator. But when we have a pointer of structure type, we use arrow (->) to access structure members.
Note that,
ptr->age is equivalent to (*ptr).age
>ptr->weight is equivalent to (*ptr).weight
Program for the same is shown in "Method 2" tab.
ptr = &p1;
Now, you can access the members of 'p1' using the 'ptr' pointer. To access members of structure using the structure variable, we used the dot (.) operator. But when we have a pointer of structure type, we use arrow (->) to access structure members.
ptr->age
ptr->weight
Note that,
ptr->age is equivalent to (*ptr).age
>ptr->weight is equivalent to (*ptr).weight
Program for the same is shown in "Method 2" tab.
Program
#include<stdio.h>
#include<conio.h>
struct person
{
char name[20];
int age;
float weight;
};
void main()
{
struct person p1;
struct person *ptr;
ptr = &p1;
printf("Enter name\t:");
scanf("%s",(*ptr).name);
printf("Enter age\t:");
scanf("%d",&(*ptr).age);
printf("Enter weight\t:");
scanf("%f",&(*ptr).weight);
printf("\n\nEntered data is");
printf("\nName\t:%s",(*ptr).name);
printf("\nAge\t:%d",(*ptr).age);
printf("\nWeight\t:%f",(*ptr).weight);
getch();
}
Output
Enter name :Nisha
Enter age :32
Enter weight :75.3
Entered data is
Name :Nisha
Age :32
Weight :75.300000