Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

Structures and

Unions
Structure

• Structure is a user-defined datatype in C language which


allows us to combine data of different types together

• Structure helps to construct a complex data type which is


more meaningful

• It is somewhat similar to an Array, but an array holds data


of similar type only but, structure on the other hand, can
store data of any type, which is practical more useful
syntax to define the structure in c.
How to create structure
Struct address
{
Char name[50];
Char street[20];
Char City[20];
Char State[20];
Int pincode;
};
Structures in C
• Heterogeneous data can be grouped together by structures in C

Syntax of a structure

struct <structure name>

datatype element 1 ;

datatype element 2 ;

datatype element 3 ;

......

};
How to declare structure
variables?
struct Point
{ int x, y;
int x, y; };
} p1; // The variable p1 is declared with 'Point'
int main()
{
struct Point p1; // The
variable p1 is declared like a
// A variable declaration like basic data types normal variable
struct Point }
{
Example for Structures
struct book

char name ;

float price ;

int pages ;

};

struct book b1, b2, b3 ;

Same as
Example for Structures
struct book

char name ;

float price ;

int pages ;

} b1, b2, b3 ;

Same as
Anonymous Structures – Structures without
name
struct

char name ;

float price ;

int pages ;

} b1, b2, b3 ;
Initialization of Structures
struct book {

char name[10] ;

float price ;

int pages ;

};

struct book b1 = { "Basic", 130.00, 550 } ;

struct book b2 = { "Physics", 150.80, 800 } ;


struct Point
{
int x, y;
};

int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
Accessing Structure Elements
To refer pages,

b1.pages

refer to price we would use,

b1.price
How to access structure
elements?
#include<stdio.h>

struct Point
{
int x, y;
};

int main()
{
struct Point p1 = {0, 1};

// Accessing members of point p1


p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);

return 0;
}
Values of One Structure Variable to Another
struct employee
{ char name[10] ;
int age ;
float salary ;
};
struct employee e1 = { "Sanjay", 30, 5500.50 } ;
struct employee e2, e3 ;
Values of One Structure Variable to Another
/* piece-meal copying */

strcpy ( e2.name, e1.name ) ;

e2.age = e1.age ;

e2.salary = e1.salary ;
Values of One Structure Variable to Another

/* copying all elements at one go */

e3 = e2 ;

printf ( "\n%s %d %f", e1.name, e1.age, e1.salary ) ;

printf ( "\n%s %d %f", e2.name, e2.age, e2.salary ) ;

printf ( "\n%s %d %f", e3.name, e3.age, e3.salary ) ; }


How
struct book
Structure Elements are Stored
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;
Example Code:
#include<stdio.h>

#include <string.h>

struct employee

{ int id;

char name[50];

}e1; //declaring e1 variable for structure

int main( )

//store first employee information

e1.id=101;

strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array

//printing first employee information

printf( "employee 1 id : %d\n", e1.id);

printf( "employee 1 name : %s\n", e1.name);

return 0;

}
#include<stdio.h> //store second employee information
#include <string.h> e2.id=102;
strcpy(e2.name, "James Bond");
struct employee e2.salary=126000;
{ int id;
//printing first employee information
char name[50];
printf( "employee 1 id : %d\n", e1.id);
float salary; printf( "employee 1 name : %s\n", e1.name);
}e1,e2; //declaring e1 and e2 variables for structure printf( "employee 1 salary : %f\n", e1.salary);
int main( )
//printing second employee information
{ printf( "employee 2 id : %d\n", e2.id);
//store first employee information
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
e1.id=101; return 0;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array }

e1.salary=56000;
Array of Structures
• It is defined as the collection of multiple structures
variables where each variable contains information about
different entities

• The array of structures in C are used to store information


about multiple entities of different data types

• The array of structures is also known as the collection of


structures.
Array of Structures

#include<stdio.h>
// Create an array of structures
struct Point struct Point arr[10];
{ // Access array members
int x, y; arr[0].x = 10;
arr[0].y = 20;
}; printf("%d %d", arr[0].x, arr[0].y);
return 0;
int main() }
{
struct book
Array of Structures
{
char name ;
float price ;
int pages ;
};
struct book b[100] ;
int i;
for ( i = 0 ; i <= 99 ; i++ )
{
printf ( "\n Enter name, price and pages " ) ;
scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
}
Array Of Structure Pointers
Like other primitive data types, we can create an array of.
Filter none

#include <stdio.h>
float points;
};
int main(void) {
// student structure variable
struct student std[3];
// student structure
// student structure pointer
struct student { variable
char id[15]; struct student *ptr = NULL;

char firstname[64]; // other variables


char lastname[64]; int i;
// assign std to ptr
ptr = std;

// get detail for user


for (i = 0; i < 3; i++) {
printf("Enter detail of student #%d\n", (i // reset pointer back to the starting
+ 1)); // address of std array
printf("Enter ID: "); ptr = std;
scanf("%s", ptr->id);
printf("Enter first name: "); for (i = 0; i < 3; i++) {
scanf("%s", ptr->firstname); printf("\nDetail of student #%d\n",
printf("Enter last name: "); (i + 1));
scanf("%s", ptr->lastname);
printf("Enter Points: "); // display result via std variable
scanf("%f", &ptr->points); printf("\nResult via std\n");
printf("ID: %s\n", std[i].id);
// update pointer to point at next element printf("First Name: %s\n",
// of the array std std[i].firstname);
ptr++; printf("Last Name: %s\n",
} std[i].lastname);
printf("Points: %f\n", std[i].points);

// display result via ptr variable


printf("\nResult via ptr\n");
printf("ID: %s\n", ptr->id);
printf("First Name: %s\n", ptr->firstname);
printf("Last Name: %s\n", ptr->lastname);
printf("Points: %f\n", ptr->points);

// update pointer to point at next element


// of the array std
ptr++;
}

return 0;
}
Limitations of C Structures

• Structures provide a method for packing together data of


different types
• A Structure is a helpful tool to handle a group of logically
related data items. However, C structures have some
limitations
• The C structure does not allow the struct data type to be
treated like built-in data types
• We cannot use operators like +,- etc. on Structure
variables
#include<stdio.h>
struct number
{
float x;
};
int main()
{
struct number n1,n2,n3;
n1.x=4;
n2.x=3;
n3=n1+n2;
return 0;
}
return 0;
Nested Structures
• Nesting of structures, is also permitted in C language. Nested structures
means, that one structure has another structure as member variable
• we may need to store the address of an entity employee in a structure.
• The attribute address may also have the subparts as street number, city, state,
and pin code. Hence, to store the address of the employee, we need to store
the address of the employee into a separate structure and nest the structure
address into the structure employee

struct Student char[50] locality;


{ char[50] city;
char[30] name; int pincode;
int age; }addr;
/* here Address is a structure */ };
struct Address
{
#include<stdio.h> struct address add;
struct address };
{ void main ()
char city[20]; {
struct employee emp;
int pin;
printf("Enter employee information?\n");
char phone[14]; scanf("%s %s %d %s",emp.name,emp.add.city,
}; &emp.add.pin, emp.add.phone);
struct employee printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone:
{
%s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
char name[20]; }
typedef in C
• typedef is a keyword used in C language to assign alternative names to
existing types.

• Its mostly used with user defined data types, when names of data types get
slightly complicated.

• Following is the general syntax for using typedef:

struct student
{
int mark [2];
char name [10];
float average;
}
1st way :
• struct student record; /* for normal variable */
struct student *record; /* for pointer variable */

2nd way :
• typedef struct student status;
• When we use “typedef ” keyword before struct <tag_name> like
above, after that we can simply use type definition “status” in the C
program to declare structure variable.
• Now, structure variable declaration will be, “status record”.
• This is equal to “struct student record”. Type definition for “struct
student” is status. i.e. status = “struct student”
//Structure using typedef: } status;

#include <stdio.h> int main()


{
#include <string.h>
status record;
record.id=1;
typedef struct student strcpy(record.name, "Raju");
{ record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
int id;
printf(" Name is: %s \n", record.name);
char name[20]; printf(" Percentage is: %f \n",
float percentage; record.percentage);
return 0;
}
Develop a C program to maintain the data of 3 books using structure
concept
title
author
subject
book_id
Surprise Gift Problem
Details of employees (emp ID, name, joining date and mobile
number) of a company is stored and maintained by the
company’s IT department. On his birthday, the GM of the
company wants to give a surprise gift of Rs.5000 for his
employees who joined before 01/01/2010 and whose
employee id is divisible by 5. Develop an algorithm and write
a C program to display the name of the employees who are
eligible to receive the gift and their mobile number
Algorithm for Surprise Gift Problem
1. Read the number of employees
2. Read the details of the employees
3. Traverse the employee records
I. Check if emp id is divisible by 5

II. If it is divisible then check if the employee has joined the company
before 01/01/2010

III. Display employee names and mobile numbers of employees if


condition satisfied
Implementation in C

• We have to store employee id, name, date of joining and


mobile number

• Date of joining has to be stored as date an user defined


data type

• So we have to include a structure variable as member of


structure
Nested Structures in C
• A structure variable can be placed inside another structure
The embedded structure enables us to declare the structure inside the
structure. Hence, it requires less line of codes but it can not be used
in multiple data structures
Identity Card for Railway
Reservation

In railway reservation system, identity of the person is got by


either Aadhar card number or voter id. Given Aadhar card
number as a number and voter id as a string. Write a C program
to store the details of thousands of people. It is important to
store such that less memory is wasted.
Note: total data limited to 10
Voter id based data: 4
Aadhar id based data:6
Using Structures?

Structure can be used to store the details but the memory


occupied will be sum of memory required for both the fields.
A large wastage when the program is used to store details of
many people
Since either one of the detail is going to be stored, it is sufficient
to allocate memory for the largest member
Supported in C as Unions!
Union in C

• Special data type available in C that allows to store different


data types in the same memory location.
• Union may have many members, but only one member can
contain a value at any given time.
• Unions provide an efficient way of using the same memory
location for multiple-purpose.
Syntax of Union
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Space Occupied by Union

#include <stdio.h>
#include <string.h>
union Data {
int aadhar;
char voterid[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data :
%d\n", sizeof(data));

return 0;
}
Accessing Union Members

• To access any member of a union, we use the member


access operator (.)
• The member access operator is coded as a period
between the union variable name and the union member
that we wish to access
• You would use the keyword union to define variables
of union type
The following example shows how to use unions in a program
#include <stdio.h> data.i = 10;
#include <string.h> printf( "data.i : %d\n", data.i);
data.f = 220.5;
union Data { printf( "data.f : %f\n", data.f);
int i;
float f; strcpy( data.str, "C Programming");
char str[20]; printf( "data.str : %s\n", data.str);
};
return 0;
int main( ) { }

union Data data;


Output:data.i : 10
data.f : 220.500000
data.str : C Programming
Features of Union

• Similar to structures
• Can have array
• Can be nested inside structures
• Structures can be nested within union
C Preprocessor and Macros

• The C preprocessor is a macro preprocessor (allows you to define macros) that


transforms your program before it is compiled

• These transformations can be the inclusion of header file, macro expansions etc
• All preprocessing directives begin with a # symbol. For example,

• For ex.
#define PI 3.14
Some of the The #include preprocessor is used to include header files to
C programs
For example,
• #include <stdio.h> common uses of C preprocessor are:
• Here, stdio.h is a header file. The #include preprocessor directive
replaces the above line with the contents of stdio.h header file.
• That's the reason why you need to use #include<stdio.h> before you
can use functions like scanf() and printf()
• You can also create your own header file containing function
declaration and include it in your program using this preprocessor
directive
• #include "my_header.h"
Macros using #define

• A macro is a fragment of code that is given a name.


You can define a macro in C using
the #define preprocessor directive.
Ex.
• #define c 299792458 // speed of light
#define preprocessor

#include <stdio.h>

#define PI 3.1415

int main()

float radius, area;

printf("Enter the radius: ");

scanf("%f", &radius);

// Notice, the use of PI

area = PI*radius*radius;

printf("Area=%.2f",area);

return 0;

}
Function like Macros

• You can also define macros that work in a similar way like a
function call
• This is known as function-like macros. For example,
#define circleArea(r) (3.1415*(r)*(r))
• Every time the program encounters circleArea(argument), it is
replaced by (3.1415*(argument)*(argument)).
• Suppose, we passed 5 as an argument then, it expands as
below:
• circleArea(5) expands to (3.1415*5*5)
Using #define preprocessor

• The #define directive causes the compiler to


substitute token-string for each occurrence
of identifier in the source file.
• The identifier is replaced only when it forms a token.
That is, identifier is not replaced if it appears in a
comment, in a string, or as part of a longer identifier
Example: #define WIDTH 80

You might also like