Accessing Structure Members Using Pointers in C


It is defined as the pointer which points to the address of the memory block that stores a structure is known as the structure pointer.
       1. To access members of a structure using pointers, we use the ( -> ) operator.
       2. The using asterisk ( * ) and dot ( . ) operator with the structure pointer

This program is an example of how to access members of a structure using a pointer in C.

  • Here, a structure called "student" is defined with three members: name, age, and per. These members are defined as a pointer to a character (string), an integer, and a floating-point number, respectively.
  • In the main function, an instance of the "student" structure is created with the name "RAM", age 25, and percentage 75.5.
  • A pointer to the structure is created and initialized with the address of the structure instance.
  • Then, the values of the structure members are accessed using the pointer, using two different methods.
  • First, the dereference operator (*) is used to access the members of the structure, combined with the dot operator (.). The value of the "name" member is accessed using the syntax (*ptr).name and printed using the printf() function.
  • Second, the arrow operator (->) is used to access the members of the structure, which is a shorthand for the previous method. The values of the "age" and "per" members are accessed using the syntax ptr->age and ptr->per, respectively, and printed using the printf() function.
  • Finally, the program ends with a return 0 statement, which indicates that the program has executed successfully.

Source Code

//Access members of structure using pointer.
 
#include<stdio.h>
 
 
struct student
{
    char *name;
    int age;
    float per;
};
int main()
{
 
    struct student o={"RAM",25,75.5};
    struct student *ptr=&o;
 
    printf("\nName    : %s",(*ptr).name);
    printf("\nAge     : %d",ptr->age);
    printf("\nPercent : %f",ptr->per);
 
    return 0;
}
 
To download raw file Click Here

Output

Name    : RAM
Age     : 25
Percent : 75.500000

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C