Dot Operator in C Programming Language
Notes:
Dot ( Member Access ) Operator in C Programming Language:
- is used to access members of a structure directly through a normal structure variable
- is used to access members of a union directly through a normal union variable
Structure:
- Structure is a collection of logically related data elements of similar or different data type.
- To represent any real world entity in a C program, we take help of a structure.
Ex:
Mathematical Application – Point, Rectangle, Circle etc.
College Management System Application – Student, Faculty, Subject etc.
Syntax for defining a Structure:
// defining a structure
struct StructureName
{
data_type variableName1;
data_type variableName2;
…
data_type variableNameN;
};
EX: // defining a Student structure
struct Student
{
int rollnum;
char *name;
float marks;
};
Syntax for declaring a Structure variable:
// declaring a structure variable
struct StructureName structureVariableName;
EX:
struct Student student1;
struct Student student2;
….
struct Student studentN;
Syntax for setting members of a Structure using Dot operator:
// setting member of a structure
structureVariableName.membername = value;
EX:
student1.rollnum = 1;
student1.name = “Suresh”;
student1.marks = 76.5;
Syntax for getting members of a Structure using Dot operator:
// getting member of a structure
structureVariableName.membername
EX:
printf(“%d\n”,student1.rollnum); // 1
printf(“%s\n”,student1.name); // Suresh
printf(“%f\n”,student1.marks); // 76.5
Example Code:
#include <stdio.h>
int main()
{
struct Student
{
int rollnum;
char *name;
float marks;
};
struct Student student1;
struct Student student2;
student1.rollnum =1;
student1.name ="Suresh";
student1.marks =76.5;
student2.rollnum =2;
student2.name ="Ramesh";
student2.marks =86.5;
printf("student1 rollnum=%d\n",student1.rollnum);
printf("student1 name=%s\n",student1.name);
printf("student1 marks=%f\n",student1.marks);
printf("\n");
printf("student2 rollnum=%d\n",student2.rollnum);
printf("student2 name=%s\n",student2.name);
printf("student2 marks=%f\n",student2.marks);
printf("\n");
return 0;
}