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

C Structures and Unions Explained

The document provides an overview of Structures and Unions in C programming, detailing their definitions, usage, and syntax. It explains how to define and access structures, initialize them, and the differences between passing structures by value and by reference. Additionally, it covers memory allocation for structures and includes multiple examples to illustrate these concepts.

Uploaded by

komaleswaris12
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 views23 pages

C Structures and Unions Explained

The document provides an overview of Structures and Unions in C programming, detailing their definitions, usage, and syntax. It explains how to define and access structures, initialize them, and the differences between passing structures by value and by reference. Additionally, it covers memory allocation for structures and includes multiple examples to illustrate these concepts.

Uploaded by

komaleswaris12
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

Structures and Unions

unit 4 Structures and Unions


Syllabus
Structures & Unions: Defining and using structures, Array of structures, Pointers to structures, Unions
and their uses, Enumerations.

STRUCTURES
Data types in C are classified into three types; namely Primitive, Derived and User-
defined. The char, int, float, double and void is the primitive data types. Array, pointers and
functions are derived data types. Enumeration, union and structures are user-defined data
types. A structure creates a data type that can be used to group items of possibly different
types into a single type. It is a collection of one or more related variables of different data
types, grouped under single name. The variables are called members of the structure.

Defining and using structures


The structure can be defined using the following syntax. The keyword struct is used alone
with the flower brackets that enclose the different member variables of the structure.
Syntax:
struct structure_name
{
data_type member_variable1;
data_type member_variable2;
……………………………;
data_type member_variableN;
};
The structure_name is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition.

Example 1
struct Address
{
char First_Name[50];
char Last_Name[50];
char Street[100];
char City[50];
char State[20];
int Zipcode;

1
Structures and Unions

};

Example 2
struct Student_Details
{
char Stud_Name[20];
int Roll_No;
int Year;
int Semester;
float Total_Marks;
char Gender;
long int Phone_no;
};

Accessing Structure
Once structure_name is declared as new data type, then variables of that type can be
declared as:
struct <structure_name> <structure_variable1>,
<structure_variable2>,….,<structure_variablen>;

The members of a structure do not occupy memory until they are associated with a
structure_variable. The structure variable can either be declared along with structure
declaration or separately declared like other basic data types.

Example 3
struct Point
{
int X_Point;
int Y_Point;
}p1, p2, p3;

Example 4
struct
{
// The struct
int X_Point;
int Y_Point;
}p1, p2, p3;

Example 5
#include<stdio.h>
struct Point
{
int X_Point;

2
Structures and Unions

int Y_Point;
};
int main()
{
// The variable p1 is declared like a normal variable struct Point p1;
}

Each variable of structure has its own copy of member variables. Individual structure
members are accessed through the use of a period, generally called the dot operator or the
member access operator (.). The member access operator is coded as a period between the
structure variable name and the structure member that we wish to [Link] structure
elements are accessed in the same way, the general form is,

structure_varname.member_name
Example 6
#include<stdio.h>
struct coordinates
{
int latitude;
int longitude;
};
int main()
{
struct coordinates deg;
// Accesing members of coordinates deg
[Link] = 20;
[Link] = 120;
printf ("x = %d, y = %d", [Link] , [Link]);
return 0;
}
Output:
x = 20, y = 120

Copying and Comparing Structure Variables


Two variables of the same structure type can be copied in the same way as ordinary
variables. If variable1 and variable1 are of the same structure type, then the following
statements are valid:

variable1 = variable2;
variable2 = variable1;
However, the statements listed below are not permitted
variable1 == variable2
variable1! = variable2
Example 7

3
Structures and Unions

#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int roll;
};
void main()
{
struct student student1={"ABC", 4};
struct student student2;
clrscr();
student2=student1;
printf("\[Link]=%s", [Link]);
printf("\[Link]=%d", [Link]);
if(strcmp([Link],[Link])==0 && ([Link]==[Link]))
{
printf("\n\n student1 and student2 are same.");
}
getch();
}
Output:
[Link]=ABC
[Link]=4
student1 and student2 are same.

Initialization of Structures
The structures in C can be initialized using the following syntax;
Syntax:
struct structure_name structure_variable={value1, value2, … , valueN};

Each variable in the structure must have a value; there must be a one to-one
correspondence between the members and their initializing values. However, the C language
does not allow the initialization of individual structure members within the structure
definition template. A compilation error is thrown if the member variables of a structure are
initialized inside the structure definition.

Example 8
#include<stdio.h>
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};

4
Structures and Unions

int main()
{
Point a;
}
Output:
int x = 0; // COMPILER ERROR: cannot initialize members here
In function 'main':
11:4: error: unknown type name 'Point'
Point a;
In C, when a datatype is declared no memory is allocated for it. Memory is allocated only
when variables are [Link] the program 4.7 failed to [Link] member variables
of a structure are always stored in contiguous memory locations. A structure variable reserves
number of bytes equal to sum of bytes needed to each of its members. 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 [Link] computer stores structures using
the concept of "word boundary". In a computer with two bytes word boundary, the structure
variables are stored left aligned and consecutively one after the other with at most one byte
unoccupied in between them called slack byte. When structure variables are declared, each
one of them may contain slack bytes and the values stored in such slack bytes are undefined.
Due to this, even if the members of two variables are equal, their structures do not necessarily
compare. That's why C does not permit comparison of structures.

The below program gives the memory allocated for a struct defined as the following;
Example 9
#include<stdio.h>
struct MemSpaceEx
{
int id;
char a;
float f;
};
int main()
{
struct MemSpaceEx struct1 = {1, 'A', 90.5};
printf("Size of structure in bytes : %d\n", sizeof(struct1));
printf("\nAddress of id printf("\nAddress of a = %u", &[Link] ); = %u", &struct1.a );
printf("\nAddress of percentage = %u",&struct1.f);
return 0;
}
Output:
Size of structure in bytes: 12
Address of id (int) = 2886254660
Address of a (char) = 2886254664
Address of f (float) = 2886254668

5
Structures and Unions

1. Initialization
Structure members can be initialized using curly braces '{}'. For example, following
is a valid initialization. In a valid initialization; the first member variable gets the first
value and second member variable gets the second value and so on. The order of
declaration is followed. This kind of initialization is also called full initialization.

Example 10
#include<Stdio.h>
struct Student_Details
{
char Stud_Name[20];
int Roll_No;
int Year;
int Semester;
float Total_Marks;
char Gender;
long int Phone_no;
};
void main()
{
struct Student_Details stud1={"Aditya.R",1,1,2,89.5, 'M', 4489078};
clrscr();
printf("Name\t\t\tRoll No.\ tYear\ tSemester\ t\ tMarks\ t \tGender\ tPhone
No.");
printf("\n...........................................\n");
printf("\n %s\t\t %d\t\t\t%d\t\t\t%d\t\t %f\t\t%c\t\t %ld",
stud1.Stud_Name,stud1.Roll_No, [Link],[Link],
stud1.Total_Marks, [Link], stud1.Phone_no);
getch();
}
Output:
Name Roll No. Year Semester Marks Gender Phone
No.

………………………………………………………………………………………………………………………………………
Aditya.R 1 1 2 89.500000 M
4489078

2. Partial initialization
Partial initialization is also allowed in C. The first few members are initialized and
the remaining is left [Link], the uninitialized members should be only at the
end of the [Link] uninitialized members are assigned default [Link] integer or

6
Structures and Unions

floating point numbers are set as Zero and '\0' is assignment for characters and strings.
The following example will explain partial initialization.

Example 11
#include<stdio.h>
struct Stud_Mentor
{
char Stud_Name[20];
int Stud_roll;
char Mentor_Name[20];
int Emp_Id;
};
void main()
{
struct Stud_Mentor s1={"Adavan.R", 1001};
clrscr();
printf(" Name=%s", s1.Stud_Name);
printf("\n Roll=%d", s1.Stud_roll);
printf("\n Mentor_Name=%s", s1.Mentor_Name);
printf("\n Emp_Id=%d", s1.Emp_Id);
getch();
}
Output:
Name=Adavan.R
Roll=1001
Mentor_Name=
Emp_Id=0

3. Designated Initialization
Designated Initialization allows structure members to be initialized in any order.
The variable name is used to assign values. Both full and partial initialization can be a
designated initialization. The below example will illustrate the designated initialization
of a structure. In the first line; pt1 is fully initialized and pt2 is partially initialized.

Example 12
#include<stdio.h>
struct D3_Point
{
int x, y, z;
};
int main()
{
// Full designated initializtion
struct D3_Point pt1 = {.y = 0, .z = 1, .x = 2};

7
Structures and Unions

// Partial designated initialization


struct D3_Point pt2 = {.x = 20};
printf ("x = %d, y = %d, z = %d\n", pt1.x, pt1.y, pt1.z);
printf ("x = %d, ", pt2.x);
printf ("y = %d", pt2.y);
return 0;
}
Output:
x = 2, y = 0, z = 1
x = 20, y = 0
Example 13 is a simple program to illustrate usage of structures in finding the sum of
two distances that are specified in feet and inches.

Example 13
#include<stdio.h>
struct Distance
{
int feet;
float inch;
};
void main()
{
struct Distance dist1, dist2, TotDist;
// Get the details of first distance
printf("Enter first distance:\n");
printf("Enter feet: ");
scanf("%d", &[Link]);
printf("Enter inch: ");
scanf("%f", &[Link]);
// Get the details of second distance
printf("\nEnter second distance:\n");
printf("Enter feet: ");
scanf("%d", &[Link]);
printf("Enter inch: ");
scanf("%f", &[Link]);
// Sum of feet and inches
[Link] = [Link]+[Link];
[Link] = [Link]+[Link];
// If inch is greater than 12, changing it to feet.
if ([Link]>12.0)
{
[Link] = [Link]-12.0;
++[Link];
}

8
Structures and Unions

printf("\nSum of distances in feet and inches = %d\' %.1f\"",[Link],


[Link]);
}
Output:
Enter first distance:
Enter feet: 23
Enter inch: 10
Enter second distance:
Enter feet: 10
Enter inch: 7
Sum of distances in feet and inches = 34'-5.0"

Example 14
#include<stdio.h>
struct telephone
{
char *Name;
int Phone_No;
};
int main()
{
struct telephone Person;
[Link] = "[Link]";
Person.Phone_No = 8012345;
printf("Name: %s\n", [Link]);
printf("Telephone number: %d\n", Person.Phone_No);
return 0;
}
Output:
Name: [Link]
Telephone number: 8012345

Structures as Function Arguments


In C, the variables can be passed in two ways to a function: 1. Passing by value (passing
actual value as argument) 2. Passing by reference (passing address of an argument) The
structure can also be passed in the above stated ways. The concept of passing structure as a
function variable is very much similar to the passing any basic data type to a function. Here is
the structure is the variable that is either passed as an address or as a value.
1. Passing structure by value
A structure variable can be passed to the function as an argument as a normal
variable. If a structure is passed by value, the changes made to the structure variable
inside the function will not reflect in the originally passed structure [Link] a
structure is used as an argument to a function, the entire structure is passed using the
standard call-by-value method. This means that any changes made to the contents of

9
Structures and Unions

the structure inside the function to which it is passed do not affect the structure used
as an argument. The receiving parameter for the passed structure must match the
type of the passed [Link] example 4.13 and 4.14 illustrates the structure as
pass by value.

Example 15
#include<stdio.h>
struct student
{
char name[10];
int age;
};
void show(struct student st);
void main()
{
struct student std;
printf("\nEnter student name :");
scanf("%s",&[Link]);
printf("\nEnter student age :");
scanf("%d",&[Link]);
//Pass by value
show(std);
}
void show(struct student st)
{
printf("\nName: %s",[Link]);
printf("\nAge : %d",[Link]);
}
Output:
Enter student name :Kavitha.K
Enter student age :15
Name: Kavitha.K
Age : 15

The below example illustrates that changes made in the function does not affect the
structure. The changes are revoked immediately after the function call is completed. The
member variable age is changed in the function show. However the change is not reflected in
the main function; the print statement after show illustrates the same.

Example 16
#include<stdio.h>
struct student
{
char name[10];

10
Structures and Unions

int age;
};
void show(struct student st);
void main()
{
struct student std;
printf("\nEnter student name :");
scanf("%s",&[Link]);
printf("\nEnter student age :");
scanf("%d",&[Link]);
//Pass by value
show(std);
printf("\nOutside the function in MAIN");
printf("\nAge : %d",[Link]);
}
void show(struct student st)
{
printf("\nInside the function");
printf("\nName: %s",[Link]);
[Link]=67;
printf("\nAge : %d",[Link]);
}
Output:
Enter student name :Adavan.R
Enter student age :8
Inside the function
Name: Adavan.R
Age : 67
Outside the function in MAIN
Age : 8

2. Passing structure by reference


The memory address of a structure variable is passed to function while passing it by
reference. If a structure is passed by reference, changes made to the structure variable
inside the function, reflects in the originally passed structure [Link] a
structure is passed by reference the called function declares a reference for the passed
structure and refers to the original structure elements through its reference. Thus, the
called function works with the original [Link] program4.15 illustrates pass by
reference of structure variables.

Example 17
#include<stdio.h>
struct student
{

11
Structures and Unions

char name[10];
int age;
};
void show(struct student *st);
void main()
{
struct student std;
printf("\nEnter student name :");
scanf("%s",&[Link]);
printf("\nEnter student age :");
scanf("%d",&[Link]);
//Pass by value
show(std);
printf("\nOutside the function in MAIN");
printf("\nAge : %d",[Link]);
}
void show(struct student *st)
{
printf("\nInside the function");
printf("\nName: %s",st->name);
st->age=67;
printf("\nAge : %d",st->age);
}
Output:
Enter student name :Adavan.R
Enter student age :8
Inside the function
Name: Adavan.R
Age : 67
Outside the function in MAIN
Age : 67

Example 18
#include<stdio.h>
struct TIME
{
int seconds;
int minutes;
int hours;
};
void diffBetnTimes(struct TIME t1, struct TIME t2, struct TIME *diff);
int main()
{
struct TIME startTime, stopTime, diff;

12
Structures and Unions

printf("Enter start time as HH MM SS: ");


scanf("%d %d %d", &[Link], &[Link],
&[Link]);
printf("Enter stop time as HH MM SS: ");
scanf("%d %d %d", &[Link], &[Link],
&[Link]);
// Calculate the difference between the start and stop time period.
diffBetnTimes(startTime, stopTime, &diff);
printf("\nTIME DIFFERENCE: %d:%d:%d - ", [Link],[Link],

[Link]);
printf("%d:%d:%d ", [Link], [Link], [Link]);
printf("= %d:%d:%d\n", [Link], [Link], . [Link]);
}
void diffBetnTimes(struct TIME start, struct TIME stop, struct TIME *diff)
{
if([Link] > [Link]) {
--[Link];
[Link] += 60;
}
diff->seconds = [Link] - [Link];
if([Link] > [Link]) {
--[Link];
[Link] += 60;
}
diff->minutes = [Link] - [Link];
diff->hours = [Link] - [Link];
}
Output:
Enter start time as HH MM SS: 12 45 34
Enter stop time as HH MM SS: 10 23 45
TIME DIFFERENCE: 12:45:34 - 10:23:45 = 2:21:49

Structure as return type


Using function we can pass structure as function argument and we can also return
structure from function. Structure is user-defined data type, like built-in data types structure
can be return from function. In the example 4.17; the

Example 19
#include<stdio.h>
struct complex_no
{
float real;
float imag;

13
Structures and Unions

};
struct complex_no add(struct complex_no n1,struct complex_no n2);
int main()
{
struct complex_no no1, no2, temp;

printf("Enter 1st complex number \n");


printf("Enter real part:");
scanf("%f", &[Link]);
printf("Enter imaginary part:");
scanf("%f", &[Link]);

printf("\nEnter 2nd complex number \n");


printf("Enter real part:");
scanf("%f", &[Link]);
printf("Enter imaginary part:");
scanf("%f", &[Link]);

temp = add(no1, no2);


printf("\t %.1f + %.1fi", [Link], [Link]);
printf("\n\t %.1f + %.1fi", [Link], [Link]);
printf("\n\t _____________");
printf("\n\t %.1f + %.1fi", [Link], [Link]);
printf("\n\t _____________");
return 0;
}
struct complex_no add(struct complex_no n1, struct complex_no n2)
{
struct complex_no temp;
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
return(temp);
}
Output:
Enter 1st complex number
Enter real part:32
Enter imaginary part:4
Enter 2nd complex number
Enter real part:11
Enter imaginary part:5

32.0 + 4.0i
11.0 + 5.0i
_____________

14
Structures and Unions

43.0 + 9.0i
_____________

1. Structure used in function without passing as argument


Like any other variable, structure variables also can be declared as global
variables. Such global structure variable is accessible by all the functions in a program.
Hence, it is not necessary to pass the structure to any function separately as argument.
The below program illustrates how the global structure student is accessed by the
function display.

Example 20
#include<stdio.h>
struct student
{
int rollno;
char name[20];
int age; float cgpa;
};
// Global declaration of structure
struct student mystud={1,"kavitha",19,9.1};
void display();
int main()
{
//Cannot initialize the global variable inside main
//mystud={1,"kavitha",19,9.1}; - will give error
printf("\n Before changes:");
display();
[Link] =20; //however the values can be changed in main
[Link] =7.9;
printf("\n After changes:");
display();
return 0;
}
void display()
{
printf("\n Rollno is: %d \n", [Link]);
printf(" Name is: %s \n", [Link]);
printf(" Age is: %d \n", [Link]);
printf(" CGPA is: %.2f \n", [Link]);
}
Output:
Before changes:
Rollno is: 1
Name is: kavitha

15
Structures and Unions

Age is: 19
CGPA is: 9.10
After changes:
Rollno is: 1
Name is: kavitha
Age is: 20
CGPA is: 7.90

ARRAY OF STRUCTURES
There can be array of structures in C programming to store information of different data
types. The array of structures is also known as collection of [Link] is used to
store the information of one particular object but if we need to store such 100 objects then
Array of Structure is [Link] structure variables and in-built data type gets same treatment
in C programming language. C language allows us to create an array of structure variable like
we create array of integers or floating point value. The syntax of declaring an array of
structure, accessing individual array elements and array indexing is same as any in-built data
type array. In the following example an array of books is created. The Book structure is used
to Store the information of a Book. To store the information of several books then an Array
of Structure is used. The variable book[0] stores the Information of 1st Book , book[1] stores
the information of 2nd Book and so on we can store the information of 100 books.

Example 21
#include<stdio.h>
struct Bookinfo
{
char Book_Name[20];
char ISBN[20];
int pages;
}book[5];

int main()
{
int i;
for(i=0;i<3;i++)
{
printf("\nEnter the Name of Book
scanf("%s",book[i].Book_Name);
printf("\nEnter the ISBN : ");
scanf("%s",book[i].ISBN);
printf("\nEnter the Number of Pages : ");
scanf("%d",book[i].pages);
printf("\n");
printf("\n");
}

16
Structures and Unions

printf("\n--------- Book Details ------------ ");

for(i=0;i<3;i++)
{
printf("\nName of Book : %s",book[i].Book_Name);
printf("\nISBN: %s",book[i].ISBN);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\n");
}
return 0;
}
Output:
Enter the Name of Book : Let Us C
Enter the ISBN : 9788176561068
Enter the Number of Pages :500

Enter the Name of Book : C How to Program


Enter the ISBN : 9788176561068
Enter the Number of Pages : 700
Enter the Name of Book : What is C?
Enter the ISBN : 9788176561068
Enter the Number of Pages :1200

--------- Book Details -----------


Name of Book : Let Us C
ISBN: 9788176561068
Number of Pages : 500
Name of Book : C How to Program
ISBN: 9788176561068
Number of Pages : 700

Name of Book : What is C?


ISBN: 9788176561068
Number of Pages : 1200

Passing an array of structure to function


Passing an array of structure type to a function is similar to passing an array of any type
to a function. The name of the array of structure is passed by the calling function which is the
base address of the array of structure. The function prototype must always be placed after
the structure definition. The program 4.20 gives a very simple usage of array of structures in
functions.

Example 22
#include<stdio.h>

17
Structures and Unions

//Structure Declaration
struct EgStruct
{
int num1;
int num2;
}s[3];
//Function to get input for the structure members
void getInput(struct EgStruct ArrEg[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter num1 : ");
scanf("%d",&ArrEg[i].num1);
printf("\nEnter num2 : ");
scanf("%d",&ArrEg[i].num2);
}
}
//Function to display the values of the structure members
void Display(struct EgStruct ArrEg[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nStructure in Array Index %d is, ", i);
printf("\nNum1 : %d",ArrEg[i].num1);
printf("\nNum2 : %d",ArrEg[i].num2);
}
}
//Main Function
void main()
{
int i;
getInput(s,3);
Display(s,3);
}
Output:
Enter num1 : 334
Enter num2 : 66

Enter num1 : 40
Enter num2 : 80

Enter num1 : 12

18
Structures and Unions

Enter num2 : 13

Structure in Array Index 0 is,


Num1 : 334
Num2 : 66

Structure in Array Index 1 is,


Num1 : 40
Num2 : 80

Structure in Array Index 2 is,


Num1 : 12
Num2 : 13

Pointers to Structures
Structures can be created and accessed using pointers. A pointer variable of a structure
can be created as below:
struct name_of_structure
{
member1;
member2;
.
.
};
int main()
{
struct name_of_structure *ptr_to_structure;
}
A structure's member can be accessed through pointer in two ways:
1. Referencing pointer to another address to access memory
2. Using dynamic memory allocation

1. Referencing pointer to another address to access memory


The below example illustrates the pointer referencing another variable which is a
structure. The pointer variable ptrBMI of type struct BMI is referenced to the address
of BMI1. Then, only the structure member through pointer can be accessed.

The structure's member variables can be accessed using-> operator


(*ptrBMI).age is same as ptrBMI->age
(*ptrBMI).weight is same as ptrBMI->weight

Example 23
#include<stdio.h>
struct BMI

19
Structures and Unions

{
int age;
float weight;
float height;
};

int main()
{
struct BMI *ptrBMI, BMI1;
ptrBMI = &BMI1;// Referencing pointer to memory address of person1

printf("Enter Age: ");


scanf("%d",&(*ptrBMI).age);

printf("Enter Weight: ");


scanf("%f",&(*ptrBMI).weight);

printf("Enter Height: ");


scanf("%f",&(*ptrBMI).height);
float bmiC = (*ptrBMI).weight/
(((*ptrBMI).height)*((*ptrBMI).weight));
printf("\nBMI Details: \n");
printf("For the age %d, weight %f, height %f, the BMI is %f",(*ptrBMI).age,
(*ptrBMI).weight,(*ptrBMI).height, bmiC);
return 0;
}
Output:
Enter Age: 45
Enter Weight: 98
Enter Height: 6.1

BMI Details:
For the age 45, weight 98.000000, height 6.100000, the BMI is 0.163934

2. Accessing structure member through pointer using dynamic memory allocation


The structure member can be accessed using pointers after allocating memory
dynamically using malloc() function. The malloc() function is defined under "stdlib.h"
header file. Hence the stdlib.h must be included in the [Link] malloc() function
takes up size in bytes are the argument and returns a ptr in a particular data type by
using type casting. Syntax for malloc() : ptr = (cast-type*) malloc(byte-size) The
program 4.20 illustrates the way to access structure variables using dynamic memory
allocation. Initially the structure array length is fetched as input from the user in the
variable num. The memory space is allocated according to the input. For each

20
Structures and Unions

BMI_Calc pointer the memory allocated is the equal to the same of memory required
for each member variable.

Example 24
#include<stdio.h>
#include<stdlib.h>
struct BMI_Calc
{
int age;
float weight;
float height;
float BMI;
};
int main()
{
struct BMI_Calc *ptrBMI;
int num,i; // Number of BMI samples planned
printf("Enter No of BMI Samples: ");
scanf("%d",&num);
ptrBMI = (struct BMI_Calc*) malloc(num * sizeof(struct BMI_Calc));
printf("Enter age, weight and height of the person respectively:\n");
for(i = 0; i < num; ++i)
{
scanf("%d%f%f", &(ptrBMI+i)->age, &(ptrBMI+i)
>weight,&(ptrBMI+i)->height);
(ptrBMI+i)->BMI = (ptrBMI+i)->weight/ ((ptrBMI+i)
>height*(ptrBMI+i)->weight);
}
printf("\nBMI for given details: \n");
printf("Age\tHeight\t\tWeight\t\tBMI\n");
for(i = 0; i < num; ++i)
{
printf("\n%d\t%f\t%f\t%f",(ptrBMI+i)->age,
(ptrBMI+i)->weight, (ptrBMI+i)->height,(ptrBMI+i)->BMI);
}
return 0;
}
Output:
Enter No of BMI Samples: 2
Enter age, weight and height of the person respectively:
23 154 78
33 170 100

BMI for given details:

21
Structures and Unions

Age Height Weight BMI


23 154.000000 78.000000 0.012821
33 170.000000 100.000000 0.010000

Unions
A structure is a user-defined data type available in C that allows to combining data
items of different kinds. Structures are used to represent a record. Like Structures,
union is a user defined data type. A union is a special data type available in C that
allows storing different data types in the same memory location. 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.

Example 25
#include<stdio.h>
#include<stdio.h>
// Declaration of union is same as structures
unionEX
{
int x, y;
};
int main()
{
// A union variable t
unionEX 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);
t.y = 10; // t.x is also updated to 10
printf("After making Y = 'A':\n x = %d, y = %d\n\n", t.x, t.y);
return0;
}
Output:
After making x = 2:
x = 2, y = 2

After making Y = 'A':


x = 10, y = 10

Difference between Unions and Structures

22
Structures and Unions

23

Common questions

Powered by AI

In C, passing structure variables by value involves passing a copy of the structure to the function, which means that any modifications inside the function do not affect the original structure variable. This is similar to passing basic data types by value, preventing changes in the function from affecting the original data . On the other hand, passing by reference involves passing the address of the structure variable to the function, allowing the function to modify the original structure directly. This method uses pointers and changes made within the function will reflect on the original variable .

When passing structures by value to a function, the contents of the structure remain unchanged after the function call, even if altered inside the function. This is due to the function working with a copy of the structure, isolating changes from affecting the original variable outside the function . Conversely, passing structures by reference involves passing their memory address, allowing the function to directly modify the structure's contents. Changes inside the function reflect on the original structure variable, as seen when using pointers for reference passing .

Dynamic memory allocation in C can be utilized with structures by using functions like malloc() to allocate memory at runtime. This approach is beneficial when the number of structures needed is not known at compile-time, allowing for flexible and efficient use of memory. For example, if a program needs to store user data that varies in number, memory can dynamically be allocated based on user input. ```c struct Student *students; int n; printf("Enter number of students:"); scanf("%d", &n); students = (struct Student *)malloc(n * sizeof(struct Student)); ``` This technique is beneficial for applications that require scalability and dynamic data handling, such as databases or user-specific settings .

User-defined data types like structures enhance the C language's capacity by allowing the grouping of different data types under a single entity, facilitating complex data management that primitive types cannot handle alone. With structures, related data of varying types can be organized and manipulated as a single coherent unit, supporting richer data models and abstractions which enable more sophisticated applications and data-structured programming, unlike primitive types that manage only single data points .

Using a pointer to a structure in C allows for dynamic data manipulation and memory efficiency, as it can directly modify the original data rather than a copy. Pointers provide flexibility in passing structures to functions, especially by reference, which can optimize both memory usage and execution speed. Unlike a regular structure variable, which uses the dot operator for member access, pointers use the arrow operator (->) to access members, enabling direct interaction with the memory address .

Using structures as global variables can be advantageous in scenarios where they need to be accessed by multiple functions or parts of a program without passing them as function arguments, reducing copying overhead . However, potential drawbacks include increased risk of unexpected side-effects due to global access, making debugging and maintaining the program more difficult, as changes can have unexpected impacts in different parts of the code .

In a C structure containing different data types, memory allocation follows a contiguous memory block layout where each member is aligned according to its data type size to comply with alignment requirements. For instance, a structure with an int and a char may have padding added to ensure the int starts at an address multiple of its size, impacting the total size of the structure due to alignment constraints. This layout ensures efficient data access but may lead to memory wastage due to padding .

The primary difference between structures and unions in terms of memory allocation is that in structures, each member variable has its own separate memory location, leading to the overall size of the structure being the sum of the sizes of all its members. In contrast, unions use a single memory location to store different types of data, with the size of the union being determined by its largest member .

An array of structures in C can be used to store related data of different types for multiple records. For instance, consider an array of structures that stores student information like name, roll number, and grades. This technique allows efficient storage and retrieval of varying data types for a list of students. Example: ```c struct Student { char name[20]; int roll_no; float grade; } students[3]; students[0].roll_no = 1; strcpy(students[0].name, "John"); students[0].grade = 88.5; ``` This allows you to store and access details for multiple students using index operations .

Copying structure variables in C can be done by direct assignment if the structures are of the same type, involving element-by-element copying of data. Comparing structures, however, is not directly supported in C as with primitive data types; instead, member-by-member comparison is required. Challenges include ensuring deep copies for structures containing pointers and the complexity of manually implementing comparison operations for all members, making efficient and reliable comparison tricky .

You might also like