0% found this document useful (0 votes)
62 views

Unit 2.2 (Structures)

Structures allow grouping of related data types under a single name. A structure defines a new custom data type that can be used to declare variables of that type. Structures help store and organize data for a single entity like a student record. Structure members are accessed using the dot operator. Padding may be added between members to align them in memory efficiently on 32-bit systems, increasing the overall structure size. The #pragma pack directive can prevent padding to minimize structure size.

Uploaded by

Karan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Unit 2.2 (Structures)

Structures allow grouping of related data types under a single name. A structure defines a new custom data type that can be used to declare variables of that type. Structures help store and organize data for a single entity like a student record. Structure members are accessed using the dot operator. Padding may be added between members to align them in memory efficiently on 32-bit systems, increasing the overall structure size. The #pragma pack directive can prevent padding to minimize structure size.

Uploaded by

Karan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

STRUCTURE

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:

Student (RollNo , Name , YearofAdmission, Branch);

I. Creating a Structure

The general syntax of a structure:


struct structure_name
{
Keyword data_type member1;
Members of a
data_type member2; Structure
data_type member3;
};
In the above example struct is a keyword while the name of structure can be any valid
identifier. The members of structure can be any of basic or derived data types. It can be
represented in C as:

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.

II. Structure Variable Declaration


 A structure can be declared in two ways:
1) Tagged Structure
 When a structure is defined, it creates a user-defined type and no memory space is
allocated by the compiler. It acts like a template to create other variable of student
type. For the above structure of student, members can be declared as:

struct student{
char EnrollNo[10];
char name[25];
int yearofAdmission;
char Branch[25];

};

Inside the main function:


struct student s1, s2; // s1, s2 are structure variables of type student

• 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, total size in bytes allocated before rounding = 10+25+4+25=64 bytes.


But, the sizeof for a struct is not always equal to the sum of sizeof of each individual
members, because of the padding added by the compiler to avoid alignment problem.
Padding is only added when a structure member is followed by a member with a larger
size or at the end of the structure.

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.

Ex. 1 Following program demonstrates the concept of C structure padding

#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};

printf("Size of structure in bytes : %d\n", sizeof(std1));

printf("\nAddress of sub1 = %u", & std1. sub1);


printf("\nAddress of sub2 = %u", & std1.Sub2);
printf("\nAddress of grade1 = %u", & std1.grade1);
printf("\nAddress of grade2 = %u", & std1. grade2);
printf("\nAddress of marks = %u",& std1. marks);

return 0;
}
OUTPUT:
Size of structure in bytes : 16

Address of sub1= 7567931

Address of sub2= 7567935

Address of grade1= 7567939

Address of grade2= 7567940

Address of marks = 7567943

Data Type Memory allocation in C (32-bit


compiler)
From Address To Address Total
Bytes
int sub1 7567931 7567934 4
int sub2 7567935 7567938 4
char grade1 7567939 1
char grade2 7567940 1
Addresses 7567941 and 7567942 are padded as 2
empty blocks
float marks 7567943 7567946 4

 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).

Ex. 2 Following program illustrates how to avoid padding in C

#include <stdio.h>
#include <string.h>

#pragma pack(1) // avoids padding between the memory allocated to the


//members
struct structure1
{
int id1;
int id2;
char name;
char c;
float percentage;
};

int main()
{
struct structure1 a;

printf("Size of structure1 in bytes : %d\n", sizeof(a));


printf ( "\n Address of id1 = %u", &a.id1);
printf ( "\n Address of id2 = %u", &a.id2);
printf ( "\n Address of name = %u",&a.name);
printf ( "\n Address of c = %u", &a.c);
printf ( "\n Address of percentage = %u", &a.percentage );
return 0;
}
OUTPUT:

Size of structure in bytes : 14


Address of id1 = 4143303844
Address of id2 = 4143303848
Address of name = 4143303852
Address of c = 4143303853
Address of percentage = 4143303854

2) Type Defined Structure


• Another way of creating structure variable using the keyword typedef is:
typedef struct student
{
char USN [10];
char name[25];
int yearofAdmission;
char Branch[25];
}STD;

OR

typedef struct {
char USN [10];
char name[25];
int yearofAdmission;
char Branch[25];
}STD;

Inside the main function:


STD s1,s2 ;

• Here the above statement declares that s1 and s2 are variables of type STD
(which is of type struct student).

III. Structure Variable Initialization


 Using the tagged method.
For ex:
struct student{
char USN [15];
char name[25];
int yearofAdmission;
char Branch[25];
};
struct student s1={“PV-1012050”,"Suresh",2020, “CSE”};

OR
struct {
char USN [15];
char name[25];
int yearofAdmission;
char Branch[25];
}student={“PV-1012043”,"Somesh",2020, “EC”};

 Using the typedef method.


For ex:
typedef struct student {
char USN [15];
char name[25];
int yearofAdmission;
char Branch[25];
}STD;

OR

typedef struct{
char USN [15];
char name[25];
int yearofAdmission;
char Branch[25];
}STD;

STD s1= {“ PV-1012065”,"Ramesh",2020, “ME”};

IV. Accessing Members of a Structure


The structure members can be accessed by using the member operator(.) dot
operator i.e structure variable name followed by dot operator followed by the name of the
structure member.

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);

 The above values can be printed as:


printf("%s", s1.name);
printf("%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

STD s1[50]; //declares s1 same as above.


To access the structure member using the array of structure:
for(i=0;i<5; i++)
{ printf(“\n Enter the USN:”);
scanf(“%s”,&s1[i].USN);
printf(“\n Enter the Name:”);
scanf(“%s”,&s1[i].name);
printf(“\n Enter the Year of Admission:”);
scanf(“%s”,&s1[i].yearofAdmission);
printf(“\n Enter the branch name:”);
scanf(“%s”,&s1[i].branch);
}

The above code will accept information of five students & store it in the array of
structure variable s1.

To print the information of five students accepted above.

printf(“\n The students details are:\n”);


for(i=0;i<5; i++)
{ printf(“\nUSN:%s”,s1[i].USN);
printf(“\nName:%s”,s1[i].name);
printf(“\nYear of Admission:%s”,s1[i].yearofAdmission);
printf(“\n Branch name:%s\n\n”,s1[i].branch);
}
VI. STRUCTURES WITHIN STRUCTURES: NESTED STRUCTURES
Whenever a structure is defined within another structure it‟s called as nested structure.
i. Using Separate Structures
Suppose the date of admission of a student is stored in another structure the earlier
structure could be rewritten as:

• 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

ii. Using Embedded Structure

Example 4:Nested structures: By Embedded structure

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;

VII.STRUCTURES AND FUNCTIONS


 structure can be passed to functions in following ways:
o Passing by value (passing actual value as argument)
o Passing by reference (passing address as an argument)

Passing Structure by Value


 A structure-variable can be passed to the function as a normal variable.
 If structure is passed by value, changes made to the structure-variable inside that
function does not reflect those changes in the calling-function.
 Example: To demonstrate passing a structure by value.

Example 5: Passing structure to a function(Call by Value)


#include<stdio.h>
struct book
{
char bname[20];
int page;
float price;
};// cannot be defined in main because it will give structure a local scope
void main()
{
struct book b1;
printf("Enter the details of the book:\n");
scanf("%s%d%f",&b1.bname,&b1.page,&b1.price);
display(b1);
}
display(struct book b2)
{
printf("The details are as follows:\n");
printf("%s\t%d\t%f",b2.bname,b2.page,b2.price);
}

OUTPUT:
Enter the details of the book:
AnsiC
354
1050
The details are as follows:
AnsiC 354 1050.000000

Passing Structure by Reference


• The address of structure variable is passed to the function.
• If structure is passed by reference, changes made to the structure variable in the
function call are also reflected in the calling-function.
• Example: Following program to multiply two integers entered by user and then store
their product into another variable.

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.

Example 6: Passing structure to a function(Call by Reference)


#include <stdio.h>
struct Calculate
{
int x,y;
int remainder, quotient;
};
void Compute(struct Calculate *p)
{
p->quotient=(p->x) /(p->y) ; //Finds the Quotient by dividing of x by y
p->remainder=(p->x) %(p->y) ; // Finds the remainder by performing x mod y
}
void main()
{
struct Calculate calc;

printf("\nEnter the first number:");


scanf("%d",&calc.x);
printf("\nEnter the second number: ");

scanf("%d",&calc.y);
Compute(&calc); //passing structure variable by reference
printf("\nQuotient is %d", calc.quotient);
printf("\nRemainder is %d", calc.remainder);
}

OUTPUT:

Enter the first number:37

Enter the second number: 12

Remainder is 1
Quotient is 3

VIII. Structure with pointer as a member of the structure

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

IX. Self referential structure


Self Referential structures are those structures that have one or more pointers which point
to the same type of structure, as their member.
Consider the following example where a structure member a pointer refers to
itself.
Ex. 7: A example of self referential structure
#include < stdio.h >

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‟;

struct node objNode2; // Node2

// Initialization
objNode2.link = NULL;
objNode2.data1 = 30;
objNode2.data2 = „R‟;

// Linking ob1 and ob2


objNode1.link = &ob2;

// Accessing data members of ob2 using ob1


printf("%d", objNode1.link->data1);
printf("\n%d", objNode1.link->data2);
return 0;
}

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

Example 9: to give a new name to a structure


#include<stdio.h>
typedef struct library //typedef in structure
{
char bname[20];
int page;
float price;
}books,textbook; //can be renamed with more than one name
void main()
{
books b1;
textbook b2; //multiple names can be given to same data type

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:

The Book1 details are


Let us C
200
200.559998
The Book2 details are
Programming in C
354
1050.500000

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:

Size of book structure= 12

Size of book union= 4

Example 2: Union illustration


#include<stdio.h>
void main()
{
union book
{
int page;
float price;
char name[20];
}b;
b.page=50;
b.price=23.56;
strcpy(b.name,"Testing");
printf("%d\n%f\n%s",b.page,b.price,b.name);
}
OUTPUT:
1953719636
77135212106908150000000000000000.000000
Testing
Explanation:
Here, values of page and price members of union got corrupted because
the final value assigned to the variable "name" has occupied the memory
location and this is the reason that the value of "name" member is getting
printed very well.

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.

int (4) char (4) int/char (4)


Fig. (a) struct Fig. (b) union

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

You might also like