0% found this document useful (0 votes)
22 views23 pages

Chapter 11 Structures

structures in c

Uploaded by

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

Chapter 11 Structures

structures in c

Uploaded by

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

Chapter 11

Structures and union


What is a Structure?
• The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language. The items in the structure are called its member and they can be of any
valid data type. Additionally, the values of a structure are stored in contiguous memory
locations.
• Structure Declaration
• We have to declare structure in C before using it in our program. In structure declaration, we
specify its member variables along with their datatype.
• Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
Example:
Struct emp
{
Char ename[20];
Int eno;
Float esal;
};
Declaring Structure Variables
• The structure is declared using the “struct” keyword. Structure allocates contiguous memory to all its member variables
• 1) Declaration of structure variables with structure definition:
• This way of declaring a structure variable is suitable when there are few variables to be declared.
Syntax:
Struct <structure_name>
{
data-type member1;
data-type member2;
………..
…………
} struct_var1,struct_var2;
EX:
Struct emp
{
Char ename[20];
Int eno;
Float esal;
} e1,e2;
2) Declaration of structure variables
separately:
• This way of creating structure variables is preferred when multiple variables are required to be declared. The structure variables
are declared outside the structure.
• Syntax:
Struct<structure_name>
{
Data-type member1;
Data-type member2;
…………………
…………………
};
Struct<structure_name> struct_var1,struct_var2,…..;
Here structure variables struct_var1 and struct_var2 are declared outside of the structure definition.
Ex:
Struct emp
{
Char ename[20];
Int eno;
Float esal;
};
Struct emp e1,e2,e3;
Initializing members of structure
• We can initialize the structure by providing the values of the members
in the list during the declaration. The values in the list will be then
assigned to the member of the structure sequentially. It means the
first value in the list will be assigned to the first member and so on.
• To initialize the structure member non-sequentially, we can use the
designated initialization technique where we initialize the members
using their names.
• Syntax to Initialize Structures in C
• structName varName = {value1, value2, value3 ..., valueN);
Example:
// C Program to illustrate how to initialize a structure
#include <stdio.h>
#include <string.h>
struct Student {
int id;
char name[50];
float percentage;
};
int main()
{
// Initialize a structure
struct Student student1 = { 1, "John Doe", 85.5 };
// Print the initialized structure
printf("ID: %d\n", student1.id);
printf("Name: %s\n", student1.name);
printf("Percentage: %.2f\n", student1.percentage);
return 0;
}
Output
Accessing Members of Structure
• We can access structure members by using the ( . ) dot operator.
• Syntax:
• <structure_variable> . <structure_member>
• Ex: e1.ename
e1.eno
e1.esal
There are many ways to assign the values to the members.
Ex:
Struct emp e1,e2;
e1.esal = 20000.00; //Assigning a value to member-esal
e1.eno = 198511; //assigning a value to member-eno
Strcpy(e1.ename,”SRIKANTH”); //assigning a value to member-ename using strcpy()
Scanf(“%s”,e2.ename); // reading value of ename of e2 through console
Structure Elements in memory
• Consider a structure of type ‘student’ and having the variables as ‘std1’ and’ ‘std2’ as shown below:
• Struct studebt
{
Char name[10];
Int age;
Char gender;
};
Struct student std1,std2;
Std1 = {“SRIKANTH”,45,’M’};
Std2={“BHAGYA”,40,’F’};
Std1 and std2 are structure variables of type struct student. The structure elements are accessed using ‘.’
operator. The structure elements are always arranged in contiguous memory locations

Std1.name std1.age std1.gender


SRIKANTH/0 45 M
Structures within structures
• A structure that contains other structure as a member, or a structure itself
is said to be “structures within structure”. I t is nothing but nesting of
structures. Structure within structure can be declared in two ways,
• 1) Declaring the structure variables as the members of another structure.
• 2) Declaring the structures themselves within another structure.
• 1) Declaring the structure variables as the members of another structure.
#include <stdio.h>
struct Address {
char city[20];
int zip;
};
struct Employee {
char name[20];
int id;
struct Address addr; // Using Address as a member of Employee
};
int main() {
struct Employee emp = {"John", 101, {"New York", 10001}};
printf("Name: %s\nID: %d\nCity: %s\nZIP: %d\n", emp.name, emp.id, emp.addr.city, emp.addr.zip);
return 0;
}
`Address` is a separate structure with `city` and `zip` fields.
`Employee` has an `Address` structure as a member, which is referenced as `addr`.
2. Declaring Structures Themselves Within Another Structure
In this method, the structure definitions are nested directly within another structure definition. Here’s an example:
#include <stdio.h>
struct Employee {
char name[20];
int id;
struct Address { // Declaring Address structure within Employee
char city[20];
int zip;
} addr;
};
int main() {
struct Employee emp = {"Alice", 102, {"Los Angeles", 90001}};
printf("Name: %s\nID: %d\nCity: %s\nZIP: %d\n", emp.name, emp.id, emp.addr.city, emp.addr.zip);
return 0;
}
In this case:
- The `Address` structure is defined inside `Employee`, and `addr` is the variable for this nested structure.
- This approach is suitable when the nested structure will only be used within the enclosing structure.
Array within structures
• An array can be declared inside a structure as a member when we need to
store multiple members of the same type.
• For example, suppose we have an employee and we need to store the data
of his/her weekly attendance. So for that, we need to
• define a structure of type Employee and store the data within that.
However, declaring and handling the 7 variables for each day
• of the week is not an easy task.

• struct Employee {
• int day1, day2, day3, day4, day5, day6, day7;
• };
C program to demonstrate the array within structures
include <string.h>
#include <stdio.h>// Defining array within structure
struct Employee { // character array to store name of the employee
char Name[20];
int employeeID;
// integer array to maintain the record of attendanc eof
// the employee
int WeekAttendence[7];
};int main()
{ // defining structure of type Employee
struct Employee emp; // adding data
emp.employeeID = 1;
strcpy(emp.Name, "Rohit");
int week;
for (week = 0; week < 7; week++) {
int attendence;
emp.WeekAttendence[week] = week;
}
printf("\n"); // printing the data
printf("Emplyee ID: %d - Employee Name: %s\n",
emp.employeeID, emp.Name);
printf("Attendence\n");
for (week = 0; week < 7; week++) {
printf("%d ", emp.WeekAttendence[week]);
}
return 0;
}
Array of structures
• In order to declare or initialize a set of structure variable at a time in a
single statement rather than one-by-one, C language permits an
‘array of structures’, where each element the array represents a
different structure variable.
• EX: struct marks student[3] = {
{“Mani,{60,95,85},0},
{“Srikanth”,{80, 80,60},0},
{“Bhagya”,{70,60,40},0}
};
Passing structure to functions
• A structure can be passed to any function from main function or from
any sub function.
• Structure definition will be available within the function only.
• It won’t be available to other functions unless it is passed to those
functions by value or by address(reference).
• Else, we have to declare structure variable as global variable. That
means, structure variable should be declared outside the main
function. So, this structure will be visible to all the functions in a C
program.
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
UNION
• The Union is a user-defined data type in C language that can contain elements of the different
data types just like structure. But unlike structures, all the members in the C union are stored in
the same memory location. Due to this, only one member can store data at the given instance.
• Syntax of Union in C
In this part, we only declare the template of the union, i.e., we only declare the members’ names
and data types along with the name of the union. No memory is allocated to the union in the
declaration.

union union_name {
datatype member1;
datatype member2;
...
};
Declaration of union variables
• Once the union datatype is created , variables can be declared as
shown below:
• Union student
{
Int age;
Char sex;
Float percent;
} u1,u2;
Union student s1,s2,s3;
Accessing members of union
• We can access the members of a union by using the ( . ) dot operator
just like structures.
var1.member1;
Ex:
S1.age = 10;
S1.gender = ‘m’,
S1.percent = 78.56
Difference between structure and
union
Advantages of structures
• Heterogeneous collection of data items: structure allows us to create user
defined data-type which can store items with different data types.
• Reduced complexity
• increased productivity: structure in C eliminates lots of burden while
dealing with records which contain heterogeneous data items, thereby
increasing productivity.
• Maintainability of code: using structure, we represent complex records by
using a single name, which makes code maintainability like a breeze.
• Enhanced code readability: code readability is crucial for larger projects.
Using structure code looks user friendly which in turn helps to maintain the
project.
Difference between arrays and
structures

You might also like