To access members of a structure using pointers, we use the -> operator.
Syntax:
#include <stdio.h>
// Define a structure
struct Person {
char name[50];
int age;
};
int main() {
// Declare a structure variable and a pointer variable
struct Person p, *ptr;
ptr=&p;
---------------------
---------------------
}
Example:
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
struct person *Ptr, p;
Ptr = &p;
printf("Enter age: ");
scanf("%d", &Ptr->age);
printf("Enter weight: ");
scanf("%f", &Ptr->weight);
printf("Displaying:\n");
printf("Age: %d\n", Ptr->age);
printf("weight: %f", Ptr->weight);
return 0;
}
Syntax:
struct test
{
char name[20];
int *age;
};
struct test t1, *ptr ;
ptr=&t1;
-------
-------
Example:
#include<stdio.h>
struct student
{
char *name[10];
int age;
char *marks[5];
};
int main()
{
struct student stu = {
"Ramesh",
25,
{77,80,75,79,65 }
};
struct student *ptr= &stu;
int i;
printf("Accessing members using structure variable: \n\n");
printf("Name: %s\n", stu.name);
printf("Age: %d\n", stu.age);
for(i = 0; i < 5; i++)
{
printf("Subject : %s \n", stu.marks[i]);
}
printf("\n\nAccessing members using pointer variable: \n\n");
printf("Name: %s\n", ptr->name);
printf("Age: %d\n", ptr->age);
for(i = 0; i < 5; i++)
{
printf("Subject : %s \n", ptr->subjects[i]);
}
return 0;
}