Lecture 3.2.1 Basics of Structure
Lecture 3.2.1 Basics of Structure
Course Objectives
CO5 Design and develop modular programs for real world problems us-
ing control structure and selection structure.
3
ASSESSMENT PATTERN
The performance of students is evaluated as follows:
Theory Practical
Continuous Internal As- Semester End Examina- Continuous Internal Semester End Exam-
Components sessment (CAE) tion (SEE) Assessment (CAE) ination (SEE)
Marks 40 60 60 40
Total Marks 100 100
4
Introduction
• Structure is a user-defined datatype in C language which allows us to combine data
of different types together.
• Structure helps to construct a complex data type which is more meaningful.
• It is somewhat similar to an Array, but an array holds data of similar type only. But
structure on the other hand, can store data of any type, which is practical more
useful.
• For example: If I have to write a program to store Student information, which will
have Student's name, age, branch, permanent address, father's name etc, which
included string values, integer values etc, how can I use arrays for this problem, I
will require something which can hold data of different types together. In structure,
data is stored in form of records.
5
Defining a Structure
• struct keyword is used to define a structure. struct defines a new data type which is a collection
of primary and derived datatypes.
• Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
...
}[structure_variables];
Note: The closing curly brace in the structure type declaration must be followed by a semicolon(;).
6
Example:
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists of 4
data fields, namely name, age, branch and gender. These fields are called structure elements
or members.
Each member can have different datatype, like in this case, name is an array of char type and
age is of int type etc. Student is the name of the structure and is called as the structure tag.
7
Declaring Structure Variables
• It is possible to declare variables of a structure, either along with
structure definition or after the structure is defined.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
• The reason for above error is simple, when a datatype is declared, no memory
is allocated for it. Memory is allocated only when variables are created.
11
Structure members can be initialized using curly braces ‘{}’. For
example, following is a valid initialization.
struct Point
{
int x, y;
};
int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
12
Computing Size of Structure
without sizeof()
• We can calculate the size of structure using pointers. Below is the implementation.
#include<stdio.h>
struct MySize
{
int a;
int b;
};
int main()
{
struct MySize *Msz=0;
int size = ((char*)(Msz+1))-((char *)(Msz));
printf("\n Structure Size :[%d]", size);
return 0;
}
Output:
Structure Size :[8]
13
Structure Padding
• The sizeof for a struct is not always equal to the sum of sizeof of each
individual member.
• This is because of the padding added by the compiler to avoid
alignment issues.
• Padding is only added when a structure member is followed by a
member with a larger size or at the end of the structure.
• Different compilers might have different alignment constraints as C
standards state that alignment of structure totally depends on the
implementation.
14
Let’s take a look at the following examples for better understanding:
Case 1:
// C program to illustrate
// size of struct
#include <stdio.h>
int main()
{
struct A {
// sizeof(int) = 4
int x;
// Padding of 4 bytes
// sizeof(double) = 8
The red portion represents the padding added for
double z;
// sizeof(short int) = 2
data alignment and the green portion represents
short int y; the struct members. In this case, x (int) is followed
// Padding of 6 bytes by z (double), which is larger in size as compared to
}; x. Hence padding is added after x. Also, padding is
printf("Size of struct: %ld", sizeof(struct A)); needed at the end for data alignment.
return 0;
}
Output:
Size of struct: 24
15
Case 2:
// C program to illustrate
// size of struct
#include <stdio.h>
int main()
{
struct B {
// sizeof(double) = 8
double z; In this case, the members of the structure
// sizeof(int) = 4 are sorted in decreasing order of their
int x; sizes. Hence padding is required only at
// sizeof(short int) = 2 the end.
short int y;
// Padding of 2 bytes
};
printf("Size of struct: %ld", sizeof(struct B));
return 0;
}
Output:
Size of struct: 16
16
Case 3:
// C program to illustrate
// size of struct
#include <stdio.h>
int main()
{
struct C {
// sizeof(double) = 8
double z; In this case, y (short int) is followed by x (int) and
// sizeof(short int) = 2 hence padding is required after y. No padding is
short int y; needed at the end in this case for data alignment.
// Padding of 2 bytes
// sizeof(int) = 4 C language doesn’t allow the compilers to
int x; reorder the struct members to reduce the
}; amount of padding. In order to minimize
printf("Size of struct: %ld", sizeof(struct C)); the amount of padding, the struct
return 0; members must be sorted in a descending
} order (similar to the case 2).
Output:
Size of struct: 16
17
Accessing Structure Members
• Structure members can be accessed and assigned values in a number
of ways.
• Structure members have no meaning individually without the
structure.
• There are two types of operators used for accessing members of a
structure.
1. . Member operator
2. -> -Structure pointer operator
18
Accessing Structure Members by
Dot
Example: Operator
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};
return 0;
}
Output:
x = 20, y = 1
19
Accessing Structure Members by
Structure pointer operator
Example:
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {1, 2};
// p2 is a pointer to structure p1
struct Point *p2 = &p1;
// Accessing structure members using structure pointer
printf("%d %d", p2->x, p2->y);
return 0;
}
Output:
12
20
Union
• Like Structures, union is a user defined data type.
• In union, all members share the same memory location.
21
For example, In the following C program, both x and y share the same location. If we change x, we can
see the changes being reflected in y.
#include <stdio.h>
// Declaration of union is same as structures
union test {
int x, y;
};
int main()
{
// A union variable t
union test t;
t.x = 2; // t.y also gets value 2
printf("After making x = 2:\n x = %d, y = %d\n\n",
t.x, t.y);
23
Structure Vs Union
24
Uses of C Structure
• C Structures can be used to store huge data. Structures act as a
database.
• C Structures can be used to send data to the printer.
• C Structures can interact with keyboard and mouse to store the data.
• C Structures can be used in drawing and floppy formatting.
• C Structures can be used to clear output screen contents.
• C Structures can be used to check computer’s memory size etc.
25
Summary
26
Frequently Asked question
Q1 What will be the output of the C program?
#include<stdio.h>
int main()
{
struct leader
{
char *lead;
int born;
};
struct leader l1 = {"AbdulKalam", 1931};
struct leader l2 = l1;
printf("%s %d", l2.lead, l1.born);
27
Q2. What will be the output of the C program?
void main()
{
struct bitfields {
int bits_1: 2;
int bits_2: 9;
int bits_3: 6;
int bits_4: 1;
}bit;
printf("%d", sizeof(bit));
}
Ans: 3
28
Q4. Write a program to Store Information in Structure and Display it?
#include <stdio.h> scanf("%s", s[i].firstName);
struct student { printf("Enter marks: ");
char firstName[50]; scanf("%f", &s[i].marks);
int roll; }
float marks;
} s[10]; printf("Displaying Information:\n\n");
29
Output:
30
Assessment Questions:
1. What is the output?
#include <stdio.h>
int main()
{
struct xyz{
int a;
};
#include<stdio.h>
int main()
{
struct simp
{
int i = 6;
char city[] = "chennai";
};
struct simp s1;
printf("%d",s1.city);
printf("%d", s1.i);
return 0;
32
4. What will be the output of the program?
#include <stdio.h>
struct cppbuzz{
};
int main()
{
printf("%d",sizeof(struct cppbuzz));
return 0;
}
33
Discussion forum.
• Watch this video to know more about how structures are stored in
memory and what is meant by structure padding.
https://www.youtube.com/watch?v=aROgtACPjjg
34
REFERENCES
Reference Books
1. Programming in C by Reema Thareja.
2. Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill.
3. Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender
Chhabra, Tata McGraw Hill.
4. The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson
education.
Websites:
5. https://www.geeksforgeeks.org/structures-c/
6. https://www.studytonight.com/c/structures-in-c.php
7. https://www.tutorialspoint.com/cprogramming/c_structures.htm
8. https://www.geeksforgeeks.org/union-c/
YouTube Links:
9. https://www.youtube.com/watch?v=Ranc3VvjI88
10. https://www.youtube.com/watch?v=zdUhS4YSWHg
35
11. https://www.youtube.com/watch?v=t7MD-Elr05k
THANK YOU