Unit 4
Unit 4
Structure {C}
Programming
Data Types
Data types are defined as the data storage format that a variable can store a data.
Data types in C
C language has built-in datatypes like primary and derived data types.
But, still not all real world problems can be solved using those data types.
We need custom datatype for different situation.
User Defined Datatype
? We need combination of various datatypes to understand different entity/object.
? Example-1:
Book Title: Let Us C Datatype: char / string
Author: Yashavant Kanetkar Datatype: char / string
Page: 320 Datatype: int
Price: 255.00 Datatype: float
? Example-2:
Student Name: ABC Datatype: char / string
Roll_No: 180540107001 Datatype: int
CPI: 7.46 Datatype: float
Backlog: 01 Datatype: int
What is Structure?
? Structure is a collection of logically related data items of different datatypes grouped
together under single name.
? Structure helps to build a complex datatype which is more meaningful than an array.
? But, an array holds similar datatype record, when structure holds different datatypes
records.
? Two fundamental aspects of Structure:
Declaration of Structure Variable
Accessing of Structure Member
Syntax to Define Structure
? To define a structure, we need to use struct keyword.
? This keyword is reserved word in C language. We can only use it for structure and its
object declaration.
Syntax
1 struct structure_namestructure_name is name of custom type
2 {
3 member1_declaration;
4 member2_declaration;
5 . . . memberN_declaration is individual member
declaration
6 memberN_declaration;
7 };
? Hence, let us learn how to create our custom structure type objects also known
as structure variable.
Example
1 struct student
2 {
3 char name[30]; // Student Name
4 int roll_no; // Student Roll No
5 float CPI; // Student CPI
6 int backlog; // Student Backlog
7 };
8 struct student student1; // Declare structure variable
Access Structure member (data)
? Structure is a complex data type, we cannot assign any value directly to it
using assignment operator.
Syntax Example
1 structure_variable.member_name; 1 // Assign CPI of student1
2 student1.CPI = 7.46;
1. Arrow operator (->)
In C language it is illegal to access a structure member from a pointer to structure variable using
dot operator.
We use arrow operator to access structure member from pointer to structure.
Syntax Example
1 pointer_to_structure->member_name; 1 // Student1 is a pointer to student type
2 student1 -> CPI = 7.46;
Write a program to read and display student information using structure.
Thank you