Unit 2.2 (Structures)
Unit 2.2 (Structures)
INTRODUCTION
Basic data types can be used to store a single value of an entity such as person, place or
thing. For ex. a person‟s name may be stored in a single variable of char array. But if more
than one attributes needs to be stored then only a single variable can‟nt solve the problem.
Alternatively, a group of attributes (such as name, age, profession etc. ) of different data
types can be group under a common name using the concept of a structure.
What is a structure?
Structure is a user defined data type with a collection of items of different or common
types grouped under a single name. Ex. Student has attributes such as Rollno,
YearofAdmission and Branch etc., this all information describes a single student. While
all these attributes can be grouped under the common name. The following structure
would contain the attributes as follows:
I. Creating a Structure
struct student{
char USN [10];
char name[25];
int yearofAdmission;
char Branch[25];
};
The variables declared inside the structure store values for a single entity student (of
Engineering) and are called members of the structure. Similarly, other examples of
structure include book, person, employee, company etc. The above
declaration can be used to declare variables of same type as student, and hence structure is
also called as user defined data type.
struct student{
char EnrollNo[10];
char name[25];
int yearofAdmission;
char Branch[25];
};
• Here, the above statement declares the variables s1 and s2 of type struct student.
• Once the structure variable are declared, the compiler allocates memory for the
structure variables.
• The size of the memory allocated is not always the sum of sizes of individual members.
For ex. in the above example:
EnrollNo: 10 x 1 byte for char =10 bytes
Name: 25 x 1 byte for char= 25 bytes
Yearof Admission: 4 bytes (assuming int to be of 4 bytes)= 4 bytes
Branch: 25x 1 bytes for char = 25 bytes
Therefore in the above case the largest size is of int ,which is 4 bytes while remaining
types have 1 bytes, hence after padding the size amounts to 68 bytes.
C – Structure Padding
In order to align the data in memory, one or more empty bytes (addresses) are
inserted (or left empty) between memory addresses which are allocated for other
structure members while memory allocation. This concept is called structure
padding.
Architecture of a computer processor is such a way that it can read 1 word (4 byte
in 32 bit processor) from memory at a time.
To make use of this advantage of processor, data are always aligned as 4 bytes
package which leads to insert empty addresses between other member‟s address.
Because of this structure padding concept in C, size of the structure is always not
same as what we think.
#include <stdio.h>
#include <string.h>
struct student
{
int sub1;
int sub2;
char grade1;
char grade2;
float marks;
};
int main()
{
int i;
struct student std1 = {90, 65, 'A', 'B', 77.5};
return 0;
}
OUTPUT:
Size of structure in bytes : 16
There are 5 members declared for structure in above program Ex. 1. In 32 bit compiler,
4 bytes of memory is occupied by int datatype. 1 byte of memory is occupied by char
datatype and 4 bytes of memory is occupied by float datatype.
The table above represents the structure with memory allocation.
HOW TO AVOID STRUCTURE PADDING IN C LANGUAGE ?
#pragma pack ( 1 ) directive can be used for arranging memory of structure members
which are of variable size and are very next to the end of other structure members.
The following program is same as the above program of example Ex. 1 but demonstrates
to avoid structure padding using the pre-processor directive #pragma pack(1).
#include <stdio.h>
#include <string.h>
int main()
{
struct structure1 a;
OR
typedef struct {
char USN [10];
char name[25];
int yearofAdmission;
char Branch[25];
}STD;
• Here the above statement declares that s1 and s2 are variables of type STD
(which is of type struct student).
OR
struct {
char USN [15];
char name[25];
int yearofAdmission;
char Branch[25];
}student={“PV-1012043”,"Somesh",2020, “EC”};
OR
typedef struct{
char USN [15];
char name[25];
int yearofAdmission;
char Branch[25];
}STD;
To access members of the student using the structure variable s1 in the above example:
s1.USN: accesses USN of any single student i.e. 2MM16CS001
s1.name: accesses Name of any single student i.e. Suresh
s1.yearofAdmission: accesses admission year of any single student i.e. 2016
s1.Branch: accesses the branch of engineering of any single student i.e. CSE
The values can be read into the members of the structure as:
gets(s1.name);
or scanf("%s", s1.name);
scanf("%d",&s1.yearofAdmission);
V. ARRAY OF STRUCTURES
The above definition of structure allows only a single instance of a variable of type
structure. But, practically the problem demands to store & process the information of more
than one student. In that case the structure variable can be declared with a size i.e by
declaring it as an array of structure.
For ex. struct student s1[50]; //declares s1 as an array of structure that can store
information of 50 students.
OR
The above code will accept information of five students & store it in the array of
structure variable s1.
• For ex:
struct DOA //DOA: Date of Admission
{
int day;
int month;
int year;
};
struct student
{
char USN [10];
char name[25];
struct DOA adm;
char Branch[25];
};
The structure declaration in the main function:
struct student s1 ,s2;
• To access the date of admission year for any student, then it would be accessed as:
s1.adm.year
Example 3:Nested structures: By separate structure
#include<stdio.h>
void main()
{
struct date
{
int day;
int month;
int year;
};
struct book
{
char name[20];
int roll;
float marks;
struct date dob;
};
int i;
struct book p[10];
printf("Enter the date of birth of the student:day,month,year\n");
scanf("%d%d%d",&p[0].dob.day,&p[0].dob.month,&p[0].dob.year);
printf("The Date of birth is:%d/%d/%d",p[0].dob.day,p[0].dob.month,p[0].dob.year);
}
OUTPUT:
Enter the date of birth of the student: day,month,year
3
12
1995
The Date of birth is:3/12/1995
struct book
{
char name[20];
int roll;
float marks;
struct date
{
int day;
int month;
int year;
}doj;
}b1;
• To access the date of admission year for any student, then it would be accessed as:
b1.doj.year;
OUTPUT:
Enter the details of the book:
AnsiC
354
1050
The details are as follows:
AnsiC 354 1050.000000
The following program demonstrates the above concept, a structure containing four
members x, y, remainder and quotient is declared. Then, the structure variable calc of
struct Calculate type is passed to the function by reference, then the remainder and
quotient is computed by accessing the x and y members of the structure and stored it in
other members quotient and remainder respectively. Then finally they are displayed in
main program.
scanf("%d",&calc.y);
Compute(&calc); //passing structure variable by reference
printf("\nQuotient is %d", calc.quotient);
printf("\nRemainder is %d", calc.remainder);
}
OUTPUT:
Remainder is 1
Quotient is 3
Consider the following program declared with a structure containing Publisher as the
pointer member.
struct Book
{
char BName[20];
char BAuthor[25];
char *Publisher;
float price;
}bok;
printf("\nBook Name: %s\n",bok.BName);
printf("Author Name: %s\n",bok.BAuthor);
printf("Publisher Name: %s\n",bok.Publisher);
printf("Price:Rs. %0.2f",bok.price);
OUTPUT:
Book Name: Programming in ANSI C
Author Name: E Balagurusamy
Publisher Name: TMH
Price: Rs. 360.00
struct node
{ int data1;
char data2;
struct node *link; //pointer to the same structure type;
};
void main()
{
struct node objNode={100,‟d‟,NULL};
if(objNode.link ==NULL)
{
objNode.link=&objNode; //points to the objNode
printf(“%d”,objNode.link->data1); //data members are accessed with an
//arrow thru the pointers
}
}
OUTPUT:
100
Ex. 8: Example
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node objNode1; // Node1
// Initialization
objNode1.link = NULL;
objNode1.data1 = 10;
objNode1.data2 = „P‟;
// Initialization
objNode2.link = NULL;
objNode2.data1 = 30;
objNode2.data2 = „R‟;
OUTPUT:
30 ObjNode1 ObjNode2
R
10 P Link 30 R Link NULL
X. Typedef
By using this keyword, the user can give a type a new name. We can define a new
name for user defined variables as well as for the per defined variables.
For Example:
typedef int INTEGER; //a normal variable example of typedef
INTEGER a=5;
printf("This is just an example of typedef:%d\n",a);
OUTPUT:
This is just an example of typedef: 5
strcpy(b2.bname,"Programming in C");
b2.page=354;
b2.price=1050.50;
strcpy(b1.bname,"Let us C");
b1.page=200;
b1.price=200.56;
printf("The Book1details are\n");
display(b1);
printf("The Book2 details are\n");
display(b2);
}
display(books b2)
{
printf("%s\n%d\n%f\n",b2.bname,b2.page,b2.price);
}
OUTPUT:
XI. Union
Union is a user defined data type and unlike structures all the members share the same
memory location. Compiler allocates storage based on the largest size of the member.
Example 1:
struct book1
{
char a;
int page;
float price;
}b1;
union book2
{
char a;
int page;
float price;
}b2;
printf("Size of book structure=%d\nSize of book union=%d",sizeof(b1),sizeof(b2));
OUTPUT:
Example 3: Union
union Device
{
int port;
int code;
};
int main()
{
union Device dvr;
dvr.port=65;
printf("port= %d code= %d\n",dvr.port,dvr.code);
printf("Size of Device = %d bytes",sizeof(Device));
return 0;
}
OUTPUT:
Port= 65 code= 65
Size of Device = 4 bytes
In the example Ex.3 declaration of union Device, all the members‟ port and code share
the same memory location of 4 bytes (on 32-bit machine). Any changes done to any
member will have the same effect on other members as well. For ex. if value of port is set
to 65 then code will also have the same value 65.
Difference between union and structure
a)
struct Device
{ int port;
char code[4];
};
b)
union Device
{ int port;
char code[4];
};
For the declaration in (a) struct Device, compiler reserves 8 bytes while in (b) it allocates 4
bytes the largest size of the member port of integer type.
Below figure shows Memory allocation of 8 bytes for struct in Fig. (a) and Fig. (b) shows
4 bytes of memory allocated to union that is the largest member port of int type.
Pointers to unions
Pointers to unions can be declared same as pointers to structures, while the union
union Device
{
int port;
char code;
};
int main()
{ union Device dvr;
union Device *ptr;
dvr.port=71;
ptr=&dvr;
printf("\nThe value through pointer:%d %c",(ptr->port), (ptr->code));
return 0;
}
OUTPUT:
The value through pointer: 71 G