KEMBAR78
Unit IV Notes | PDF | Pointer (Computer Programming) | Scope (Computer Science)
0% found this document useful (0 votes)
17 views22 pages

Unit IV Notes

Uploaded by

Dharshan
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)
17 views22 pages

Unit IV Notes

Uploaded by

Dharshan
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/ 22

Unit – IV

STRUCTURES AND UNIONS


=======================================================================
Structures - Definition, Declaration, Initialization; Nesting of structures – Pointer and
Structures, Array of structures, Self-referential structures; Union - Declaring unions,
Declaring variables and pointers to unions, Access members, operations on union; Storage
classes.

=======================================================================

Structures and Unions

Structure

A structure is a user defined data type. We know that arrays can be used to represent a
group of data items that belong to the same type, such as int or float. However we cannot use an
array if we want to represent a collection of data items of different types using a single name.

A structure is a convenient tool for handling a group of logically related data items. Structure
is a user defined data type used to represent a group of data items of different types using a single
name.

The syntax of structure declaration is

struct structure_name
{
type element 1;
type element 2;
……………..
type element n;
};

In structure declaration the keyword struct appears first, this followed by structure
name. The member of structure should be enclosed between a pair of braces and it defines
one by one each ending with a semicolon. It can also be array of structure. There is an
enclosing brace at the end of declaration and it end with a semicolon.

1
We can declare structure variables as follows

struct structure_name var1,var2,…..,var n;

Example:

To store the names, roll number and total mark of a student you can declare 3 variables. To store
this data for more than one student 3 separate arrays may be declared. Another choice is to make a
structure.
 No memory is allocated when a structure is declared.
 It just defines the “form” of the structure.
 When a variable is made then memory is allocated.
 This is equivalent to saying that there's no memory for “int”, but when we declare
an integer that is int var; only then memory is allocated.
 The structure for the above mentioned case will look like

struct student
{
int rollno;
char name[25];
float totalmark;
};

We can now declare structure variables stud1, stud2 as follows

struct student stud1,stud2;

Thus, the stud1 and stud2 are structure variables of type student. The above structure can hold
information of 2 students. It is possible to combine the declaration of structure combination with that
of the structure variables, as shown below.

struct structure_name
{
type element 1;
type element 2;
……………..

2
type element n;
} var1,var2,…,varn;

The following single declaration is equivalent to the two declaration presented in the
previous example.

struct student
{
int rollno;
char name[25];
float totalmark;
} stud1, stud2;

Accessing structure Variable

 The different variable types stored in a structure are called its members.
 The structure member can be accessed by using a dot (.) operator, so the dot operator is
known as structure member operator.

Example:

 In the above example stud1 is a structure variable of type student.


 To access the member name, we would write stud1.name.
 Similarly, stud1’s rollno and stud1’s totalmark can be accessed by writing stud1.rollno and
stud1.totalmark respectively.

Initializing Structure Members

 Structure members can be initialized at declaration.


 This much the same manner as the element of an array; the initial value must appear in the
order in which they will be assigned to their corresponding structure members, enclosed in
braces and separated by commas.
 The general form is

struct structure_name var={val1,val2,val3…..};

3
Example:

#include <stdio.h>
#include<conio.h>
void main()
{
struct student
{
char *name;
int rollno;
float totalmark;
};
struct student stud1={"Venkat",1,98};
struct student stud3= {"Shweta",3,97};
struct student stud2={"Arpita",2,99};
clrscr();
printf(“STUDENTS DETAILS:\n”);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, stud1.rollno, stud1.name,
stud1.totalmark);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, stud2.rollno, stud2.name,
stud2.totalmark);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, stud3.rollno, stud3.name,
stud3.totalmark);
getch();
}

Output:

STUDENTS DETAILS:
Roll number: 1
Name: Venkat
Total Marks:98.000000
Roll number: 2
Name: Arpita
Total Marks:99.000000
Roll number: 2

4
Name:Shweta
Total Marks:99.000000

Structure as structure member (Nesting of Structure/Embedded Structure):

 A structure inside another structure is called an embedded structure.


 A structure can have one or more of its member as another structure, but a structure cannot
be member to itself when a structure is used as structure member.
 In such situation, the declaration of the embedded structure must appear before the
declaration of the outer structure.
For example

#include <stdio.h>
#include <conio.h>
void main()
{
struct dob
{
int day;
int month;
int year;
};
struct student
{
struct dob d;
int rollno;
char name[25];
int totalmark;
}stud[25];
int n,i;
clrscr();
printf("Enter total number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnter details of %d student",i+1);

5
printf("\nName:");
scanf("%s",&stud[i].name);
printf("\nRoll number:");
scanf("%d",&stud[i].rollno);
printf("\nTotal mark:");
scanf("%d",&stud[i].totalmark);
printf("\nDate of birth (Format:01 06 2010):");
scanf("%d%d%d",&stud[i].d.day,&stud[i].d.month,&stud[i].d.year);
}
printf("\nSTUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRoll number:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Total mark:%d\n",stud[i].totalmark);
printf("Date of birth : %d / %d / %d \n\n",
stud[i].d.day,stud[i].d.month,stud[i].d.year);
}
getch();
}

OUTPUT

Enter total number of students 2


Enter details of 1 student
Name: karthik
Roll number:12
Total mark:588
Date of birth (Format:01 06 2010):11 12 1997
Enter details of 2 student
Name: sarita
Roll number:18
Total mark:598
Date of birth (Format:01 06 2010):1 2 1997

STUDENTS DETAILS:
Roll number:12

6
Name: karthik
Total mark: 588
Date of birth : 11 / 12 / 1997
Roll number:18
Name: sarita
Total mark:598
Date of birth : 1 / 2 / 1997

Pointer and Structure

 For representing complex data structures,we can use structures and pointers together.
 Pointer can be member of structure or pointer to structure or an array of pointers to
structure.

For Example:

struct student
{
int roll_no;
char name[20];
char address[30];
int age;
}s1,*sptr; ………. ……….. sptr=&s1;

 Now,sptr points to s1 and can be used to access member variables of struct student.
 To access member variables using pointer to structure, we have to use an arrow ->
operator.

The Syntax is:


struct_pointer->member_var;
 The struct_pointer is a pointer to structure, and member_var is the name of member
variable.
For Example:
S1→roll_no=20;
 We can also use dot(.)operator to access member variable like: (*s1).roll_no=20;
 Both above statements do the same things.

7
Array of structures:

 It is possible to store a structure has an array element. i.e., an array in which each
element is a structure.
 Just as arrays of any basic type of variable are allowed, so are arrays
of a given type of structure.
 Although a structure contains many different types, the
compiler never gets to know this information because it is hidden away inside a sealed
 structure capsule, so it can believe that all the elements in the array have the same type,
even though that type is itself made up of lots of different types.

The declaration statement is given below.

struct struct_name
{
type element 1;
type element 2;
……………..
type element n;
}array name[size];

Example:

struct student
{
int rollno;
char name[25];
float totalmark;
} stud[100];

 In this declaration stud is a 100-element array of structures.


 Hence, each element of stud is a separate structure of type student.
 An array of structure can be assigned initial values just as any other array.
 So the above structure can hold information of 100 students.

8
Program to demonstrate use of array of structure

#include <stdio.h>
#include <conio.h>
void main()
{
struct student
{
int rollno;
char name[25];
int totalmark;
}stud[100];
int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details of %d-th student\n",i+1);
printf("Name:\n");
scanf("%s",&stud[i].name);
printf("Roll number:\n");
scanf("%d",&stud[i].rollno);
printf("Total mark:\n");
scanf("%d",&stud[i].totalmark);
}

printf("STUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRoll number:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Total mark:%d\n",stud[i].totalmark);
}
getch();
}

9
OUTPUT

Enter total number of students:


3
Enter details of 1-th student
Name:SUBAHAS
Roll number:11
Total mark:589
Enter details of 2-th student
Name:RUKSANA
Roll number:12
Total mark:594
Enter details of 3-th student
Name:SANA
Roll number:13
Total mark:595
STUDENTS DETAILS:
Roll number:11
Name: SUBAHAS
Total mark:589
Roll number:12
Name: RUKSANA
Total mark:594
Roll number:13
Name: SANA
Total mark:595

Self Referential Structures

Self Referential structures are those structures that have one or more pointers which point to the
same type of structure, as their member.

struct node {
int data1;
char data2;
struct node* link;
};

10
int main()
{
struct node ob;
return 0;
}

In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a
self-referential structure with ‘link’ as the referencing pointer.

An important point to consider is that the pointer should be initialized properly before accessing, as
by default it contains garbage value.

Types of Self Referential Structures

1.Self Referential Structure with Single Link


2.Self Referential Structure with Multiple Links

1.Self Referential Structure with Single Link:

These structures can have only one self-pointer as their member. The following example will show
us how to connect the objects of a self-referential structure with the single link and access the
corresponding data members

#include <stdio.h>

struct node {
int data1;
int data2;
struct node* link;
};

int main()
{
struct node ob1; // Node1

// Initialization

11
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2

// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

// Linking ob1 and ob2


ob1.link = &ob2;

// Accessing data members of ob2 using ob1


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

Output

30
40

2. Self Referential Structure with Multiple Links:

Self referential structures with multiple links can have more than one self-pointers. Many
complicated data structures can be easily constructed using these structures. Such structures can
easily connect to more than one nodes at a time. The following example shows one such structure
with more than one links.

#include <stdio.h>

struct node {
int data;
struct node* prev_link;

12
struct node* next_link;
};

int main()
{
struct node ob1; // Node1

// Initialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;

struct node ob2; // Node2

// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;

struct node ob3; // Node3

// Initialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;

// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;

// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;

// Accessing data of ob1, ob2 and ob3 by ob1


printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);

13
printf("%d\n", ob1.next_link->next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob2


printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
printf("%d\n", ob2.next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob3


printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
return 0;
}

Output

10 20 30
10 20 30
10 20 30

Typedef:

The typedef is a keyword that is used to provide existing data types with a new name. The C
typedef keyword is used to redefine the name of already existing data types.When names of
datatypes become difficult to use in programs, typedef is used with user-defined datatypes, which
behave similarly to defining an alias for commands.

Synatx

typedef existing_name alias_name;

Example

typedef unsigned int unit;

Sample Program

14
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
Output
Value of i is :10
Value of j is :20

Union

A union is declared and used in the same ways that a structure. Unions are defined and declared in
the same fashion as structures.
In unions, all the members share the space which is according to the space requirement of the
largest member. The union can hold only one value at a time. A union can be initialized on its
declaration.
Because only one member can be used at a time, only one can be initialized. To avoid confusion,
only the first member of the union can be initialized.

Defining of Union

A union has to defined, before it can be used.

The syntax of defining a union is

union <union_name>
{

15
<data_type> <variable_name>;
<data_type> <variable_name>;
………….
<data_type> <variable_name>;
};

Example

To define a simple union of a char variable and an integer variable

union shared
{
char c;
int i;
};

This union, shared, can be used to create instances of a union that can hold either a
character value(c) or an integer value( i ).

For example, the following code declares a union data type called Student and a
union variable called stud:

union student
{
int rollno;
float totalmark;
};
union student stud;

It is possible to combine the declaration of union combination with that of the union
variables, as shown below.

union union_name
{
type element 1;
type element 2;
……………..

16
type element n;
}var1,var2,…,varn;

The following single declaration is equivalent to the two declaration presented in the
previous example.
union student
{
int rollno;
float totalmark;
}x,y,z;

Accessing members of union using pointers:


We can access the members of the union through pointers by using the (->) arrow operator.

Let's understand through an example.

#include <stdio.h>
union abc
{
int a;
char b;
};
int main()
{
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}

In the above code, we have created a pointer variable, i.e., *ptr, that stores the address of var
variable. Now, ptr can access the variable 'a' by using the (->) operator. Hence the output of the
above code would be 90.

17
Difference between Structure and Union:

Structure Union

It can be defined using struct keyword It can be defined using a union keyword.

Every member within structure is assigned a In union, a memory location is shared by all
unique memory location. the data members.

Changing the value of one data member will Changing the value of one data member will
not affect other data members in structure. change the value of other data members in
union.

It allows initializing several members at It allows initializing only the first member of
once. union

The total size of the structure is the sum of The total size of the union is the size of the
the size of every data member. largest data member.

It is used for storing various data types. It is used for storing one of the many data
types that are available.

It reserves space for each and every It reserves space for a member having the
member separately. highest size.

Any member can be retrieve at a time. Only one member can be retrieve at a time.

It allows dynamic array as member. It does not allows dynamic array as member.

Storage Class

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C
Program. They precede the type that they modify. We have four different storage classes in a C
program
1. auto
2. register
3. static
4. extern
The auto Storage Class
The auto storage class is the default storage class for all local variables.
{

18
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be used
within functions, i.e., local variables.
The register Storage Class
 The register storage class is used to define local variables that should be stored in a register
instead of RAM.
 This means that the variable has a maximum size equal to the register size (usually one
word) and can't have the unary '&' operator applied to it (as it does not have a memory
location).
{
register int miles;
}
 The register should only be used for variables that require quick access such as counters.
 It should also be noted that defining 'register' does not mean that the variable will be stored
in a register.
 It means that it MIGHT be stored in a register depending on hardware and implementation
restrictions.
The static Storage Class
 The static storage class instructs the compiler to keep a local variable in existence during
the life-time of the program instead of creating and destroying it each time it comes into and
goes out of scope.
 Therefore, making local variables static allows them to maintain their values between
function calls.
 The static modifier may also be applied to global variables.
 When this is done, it causes that variable's scope to be restricted to the file in which it is
declared.
 In C programming, when static is used on a global variable, it causes only one copy of that
member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {

19
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

The extern Storage Class


 The extern storage class is used to give a reference of a global variable that is visible to ALL
the program files.
 When you use 'extern', the variable cannot be initialized however, it points the variable name
at a storage location that has been previously defined.
 When you have multiple files and you define a global variable or function, which will also be
used in other files, then extern will be used in another file to provide the reference of defined
variable or function.
 Just for understanding, extern is used to declare a global variable or function in another file.
 The extern modifier is most commonly used when there are two or more files sharing the
same global variables or functions as explained below.

First File: main.c


#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();

20
}
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void) {
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its definition in the
first file, main.c. Now, compile these two files as follows −
$gcc main.c support.c
It will produce the executable program a.out. When this program is executed, it produces the
following result
count is 5

Important questions

PART A

1. Define Structure in C.
2. Write the syntax to Declare a members in Structure.
3. What are the Rules for declaring a structure?
4. How to initialize structures in „C‟? Write example.
5. Define a structure type personal, that would contain person name, date of joining and salary.
Write a program to initialize one person data and display the same.
6. How to access the data for structure variables using member operator(“.‟)?
7. What is an array of structure?
8. What is structure within structure? Give an example for it
9. What is self- referential structure? Explain through example.
10. Define structure pointers.
11. What is union?
12. What are * and & operators means?
13. What are the advantages of unions over structures?
14. Write the syntax for pointers to structure.
15. What is the primary purpose of using a structure in C programming?
16. Differentiate between a structure and a union in C programming.
17. Explain the concept of padding in the context of structures in C.

21
18. Write a C structure declaration for representing a book with attributes: title, author, and
price.
19. Define storage classes
20. What are the storage classes available in C?
21. Define auto storage class.
22. Define static storage class.
23. Define register storage class.
24. Define extern storage class.

Part-B
1. Describe the Structures in C Programming
2. With examples illustrate the difference between structure and union in C
3. Create a payroll application using structure with the following details :
DA= 15% of basic
HRA= 20% of basic
TA=18% of basic
Gross salary = basic + HRA + DA + TA
Deduction = PF + tax;
Net Salary =Gross Salary – Deduction
4. Write a C program using structure to print the details of book. Use array of structure
5. Write the syntax for structure declaration with an example
6. List the procedure and write the syntax for structure initialization with an example
7. Illustrates pointer to structure with an example C program
8. Clarify the accessing of structure variables with an example
9. How to create array of structure in C? Explain with an example program.
10. Write a program to print students register number, name, marks and grade using unions.
11. Examine the nested structures in C with an example
12. Describe how to declare, initialize and access members of Union with a programming exam-
ple
13. Develop a C Program to use the arrays inside union variables.
14. How to declare and access the union variable in C programming? Explain with an example
15. Describe about self referential structure in C Programming with an example
16. List and explain the different types of storage classes with an example
17. Analyse pointers to union with an example program
18. Write a C program using union, to prepare the employee pay roll of a company

22

You might also like