0% found this document useful (0 votes)
6 views9 pages

Structures & Union

The document explains the concept of structures and unions in the C programming language, detailing how to define, initialize, and manipulate these custom data types. It covers structure variables, arrays of structures, nested structures, and methods for passing structures to functions, as well as the differences between structures and unions. Key examples illustrate the syntax and usage of these data types, emphasizing memory conservation and data organization.

Uploaded by

layih72926
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)
6 views9 pages

Structures & Union

The document explains the concept of structures and unions in the C programming language, detailing how to define, initialize, and manipulate these custom data types. It covers structure variables, arrays of structures, nested structures, and methods for passing structures to functions, as well as the differences between structures and unions. Key examples illustrate the syntax and usage of these data types, emphasizing memory conservation and data organization.

Uploaded by

layih72926
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/ 9

Structures

The C language allows us to create custom data types. The structure is a custom data type which c
combines different data types .The structure is a custom data type which combine different data types to
form a new user define data type.
Structure definition
A structure is a collection of variable reference under one name providing a convincible means of related
information together.
Format:
struct tag_name
{
data _type member1;
data_type member2;
-------------------
---------------------
};
here a keyboard struct declares a structures to hold the details of field of different data types.
Example:
struct addr
{
char name [30];
char city [15];
int pincode ;
};
Creating Structure variable
Structure variable can be created in two ways:
1. Declaration using tag_name anywhere in the program.
Example:
struct book
{
char name [30];
char author [25];
float price;
};
struct book book1, book2
2. it is also allowed to combine structure declaration and variable declaration in one statement.
Example:
struct person
{
char *name;
int age;
char*address;
} p1, p2, p3;
Image showing how the given value allocate in structure with the help of an example >

Giving Values to Member


The link between a member and a variable is established using member operator `.' to dot operator.
An example program to define a structure and assign value to members:
Structure Initialization
A structure variable can be initialization as any other data type.
main()
{
Struct student
{
int weight;
float height;
}
struct student s1{60, 180.75};
}
This assign the value 60 to student weight and 180.75 student height. There is a one to one
correspondents between the members and their initializing values.

Arrays of Structures
The most common use of structures is in arrays of structures. To declare an array of structures, first the
structure is defined then an array variable of that structure is declared.
Example:
struct class student [100];
It defines an array called student which consists of 100 elements of structure named class.
Array within structures
Single as multidimensional arrays of type int and float can be defined as structure members.
Example:
struct marks
{
int number;
float subject[3];
}
student [2];
Here the member subject contains three elements, subject[0], subject[1] and subject[2] there elements
can be accessed using appropriate subscript. For instance, the name student [1] student [2]; would refer
to the marks obtained in the third subject by the secured student.
Structures within structures
Structures within a structure means nesting of structures.
Example:
struct salary
{
char name [20];
char department [10];
int basic-pay;
int dearness-allowance;
int house_rent_allowance;
int city_allowance;
} employee;
This structure defines name, department, basic pay and three kinds of allowances. All the items related
to allowance can be grouped together and declared under a sub-stricture. As shown below,

struct salary
{
char name []2;
char department [10];
struct
{
int dearness;
int house_rent;
int city;
}allowance;
} employee;

The salary structure contains a member named allowance which use is a structures with. Three
members. Now ; the member compared in the inner structure;, namely, ;dearness, house_rent and city
can ;be left to as;
employee.allowance.dearness
employee.allowance.house_rent
employee.allowance.city

The inner most member in a nested structure can be accessed by chaining all the concerned structure
variables (from outermost to inner most) with the member using dot operator.

Passing structure to Function


There are three methods by which the values of structure can be transferred from one function to
another:
1. The first method is to pass each member of the structure as an actual argument of the function call.
The actual argument is then treated independently like ordinary variables.
2. The second methods involve passing of a copy of the entire structure to the called function .Since the
function is working on a copy of the entire structure to the called function, changes are not reflected in
the original structure (in the calling function).It is necessary for the entire function to return the entire
structure back to the calling function.
3. The third approach employs a concept called pointers to pass the structure as an argument .In this
case, the address location of the structure is passed to the called function. The function can access
indirectly the entire structure and work on it.
The general format of sending a copy of structure to the called function is:
function_name (structure_variable_name)
Passing Structure to function
In C, we can pass structure to a function in 3 different ways:
 Passing structure members as arguments
 Passing structure variable as argument
 Passing pointers to structure as argument
Passing structure members as argument
We can pass the members of structure as argument to a function.
Example
#include<stdio.h>
void display(int rollno,char nm[],int marks); //declaration of the function
struct student //declaration of structure
{
int rollno;
char nm[10];
int marks;
};
void main()
{
struct student s1={01,“Mary”,65}; //Initializing the members of the structure
display(s1.rollno,s1.nm,s1.marks);
}
void display(int rollno,char nm[],int marks) //definition of function
{
printf(“Student details are:\n”);
printf(“\nRoll no: %d”,rollno);
printf(“\nName: %s”,nm);
printf(“\nMarks: %d”,marks);
}
Output:
Student details are:
Roll no: 01
Name: Mary
Marks: 65
Here the members of the variable s1 is passed as argument to function display().

Passing structure variable as argument


We can pass the entire structure as argument to a function instead of passing the members of structure.
Passing the structure members as argument becomes tedious when the number of members in the
structure increases, therefore it is convenient to pass structure as argument instead.
Example:
#include<stdio.h>
struct student //declaration of structure
{
int rollno;
char nm[10];
int marks;
};
void display(struct student); //declaration of the function
void main()
{
struct student s1={01,“Mary”,65}; //Initializing the members of the structure
display(s1);
}
void display(struct student s1) //definition of function
{
printf(“Student details are:\n”);
printf(“\nRoll no: %d”,s1.rollno);
printf(“\nName: %s”,s1.nm);
printf(“\nMarks: %d”,s1.marks);
}
Output:
Student details are:
Roll no: 01
Name: Mary
Marks: 65

Passing pointers to structure as argument to a function


If the size of the structure is large, it is inconvenient to pass the entire structure to the function as
argument because the function will create a copy of the same.
In such case, it is better to send address of the structure as argument, that will increase the execution
time. Also the changes made to the members of structure inside the called function is reflected in the
calling function also, since all the operations are performed on the original members itself.
Example:
#include<stdio.h>
struct student //declaration of structure
{
int rollno;
char nm[10];
int marks;
};
void display(struct student *); //declaration of the function
void main()
{
struct student s1={01,“Mary”,65}; //Initializing the members of the structure
display(&s1);
}
void display(struct student *s1) //definition of function
{
printf(“Student details are:\n”);
printf(“\nRoll no: %d”,s1->rollno);
printf(“\nName: %s”,s1->nm);
printf(“\nMarks: %d”,s1->marks);
}
Output:
Student details are:
Roll no: 01
Name: Mary
Marks: 65
Union
Union are derived data types, the way structure are. Though, unions and structures look alike, and there
is a fundamental difference.
While structure enables you to create a number of different variables stored in difference places in
memory, unions enable you to treat the same space as a number of different variables.
Union-Definition and Declaration
Unions, like structures, contain members whose individual data types may differ from one another.
However, the members within a union all share the some storage space within the computer's memory,
whereas each member within a structure is assigned its own unique storage area.
Thus, unions are used to conserve memory.
They are useful for applications involving multiple members, where values need not be assigned to all of
the members at any one time.
Within a union, the bookkeeping required to store members whose data types are different (having
different memory requirements) is handled automatically to the compiler.
However, the user must keep track of what type of information is stored at any given time.
An attempt to access the wrong type of information will produce meaningless results.
In general terms, the composition of a union may be defined as:

union tag_name
{
member 1;
member 2;
…..
member n;
};
Where union is required keyword and the other terms have the same meaning as in a structure
definition.
Individual union variables can then be declared as:
storage-class union tag variable 1, variable 2, . . . , variable n;
Where storage-class is an optional storage class specified, union is a required keyword, tag is the name
that appears in the union definition, and variable 1, variable 2, . . . , variable n are union.
The two declarations may be combined, just as we did with structures. Thus, we can write Storage-class
union tag
{
member 1;
member 2;
.....
member n;
}

The tag is optional in this type of declaration.


Notice that the union and structure declarations are external to the program functions, but the structure
variable is defined locally within each function.
Accessing a Union Member
To access a union member, you can use the same syntax that you use for structure members.
Example:
code.m, code.x etc.
During execution, we should make sure that the value of accessing member is currently stored.

Initialization of a Union Variable


A union variable can be initialized , provided its storage class is either external or static. Only one
member of a union can be assigned a value at any one time.
The initialization value is assigned to the first member within the union.
An example program to demonstrate initialization of union variables:

Uses of Union
Union, like structure, contain members whose individual data type may differ to each other.
But the members that compose a union share the same storage area within the computer's memory,
whereas each member within a structure is assigned its own unique storage area.
Thus, union are used to conserve memory.
1. Unions are useful for application involving multiple members, where value need not to be assigned to
all of the members at any one time.
2. Unions are useful whenever there is a requirement to access the same memory location in more than
one way. etc.
Difference between Structure & Union
Structure Union
Keyword The struct keyword is used while The union keyword is used while
defining structure defining union
Initialization The members of the structures can All the members of the union cannot
be initialized simultaneously be initialized simultaneously only first
member of the union can be
initialized
Memory In structure, all the members has its In union, all the members share same
location own memory location memory location
Size The memory allocated for structure The compiler allocates memory for
variable by the compiler, is greater the union by considering the size of
than or equal to sum of the sizes of largest member so the size allocated
its members by union is equal to size of the largest
member

You might also like