0% found this document useful (0 votes)
17 views85 pages

Unit_1_Part_4

The document provides an introduction to structures, unions, and dynamic memory allocation in C programming. It details how to create and initialize structures, access their members, and the differences between structures and unions, including memory management techniques. Additionally, it covers abstract data types (ADTs) and their significance in defining operations without specifying implementation details.

Uploaded by

singhkirat4224
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)
17 views85 pages

Unit_1_Part_4

The document provides an introduction to structures, unions, and dynamic memory allocation in C programming. It details how to create and initialize structures, access their members, and the differences between structures and unions, including memory management techniques. Additionally, it covers abstract data types (ADTs) and their significance in defining operations without specifying implementation details.

Uploaded by

singhkirat4224
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/ 85

Unit-1: Introduction

STRUCTURE, UNION, Dynamic


Memory Allocation, ADTs
Structures in C
 A Structure is a user defined data type that can store related
information together. (Unlike arrays which permit a programmer to
group only elements of same data types)
 The variables are called members of the structure
How to create a structure?
‘struct’ keyword is used to create a structure. Example

This tells the compiler how big our struct is and how the different data
items (“members”) are laid out in memory. But it does not allocate
any memory
Structures declaration in C
How to declare structure variables?
A structure variable can either be declared with structure declaration or
as a separate declaration like basic types.

A variable declaration with A variable declaration like basic


structure declaration. data types

Defines a structure variable named s and s1


Example:
initializing structure members
How to initialize structure members?
Structure members cannot be initialized with declaration. For example
the following C program fails in compilation.

The reason for above error is simple, when a datatype is declared,


no memory is allocated for it. Memory is allocated only when
variables are created.
Initializing structure members
 Structure members can be initialized using curly braces ‘{}’. For
example, following is a valid initialization.
Initialization of string in structure
Below program will give error if we are initializing string using s1.mystring=“some text”.
We can initialize the string at the time of declaring structure variable or using functions such as scanf, gets, strcpy.
Designated Initialization
 Designated Initialization allows structure members to be initialized in
any order. This feature has been added in C99 standard.
 This feature is not available in C++ and works only in C.
HOW STRUCTURE MEMBERS ARE STORED IN
MEMORY?
 Always, contiguous(adjacent) memory locations are used to store structure members
in memory. Consider below example to understand how memory is allocated for
structures.
Refer the program here
structsize.c

 There are 5 members declared for structure in above program. 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 datatype.
How to minimize structure padding?
 There is a way to minimize padding. The programmer should declare the
structure members in their increasing/decreasing order of size. An example is
structd_t given in our code, whose size is 16 bytes in lieu of 24 bytes of
structc_t.
How to access structure
elements?
How to access structure elements?
Structure members are accessed using dot (.) operator.
C – Array of Structures
 C Structure is collection of different datatypes ( variables ) which are grouped
together. Whereas, array of structures is nothing but collection of structures. This
is also called as structure array in C.
 This program is used to store and access “id, name and percentage” for 3
students. Structure array is used in this program to store and display records for
many students. You can store “n” number of students record by declaring
structure variable as ‘struct student record[n]“, where n can be 1000 or 5000 etc.

Refer the program here structarr.c


Nested Structures
Typedef
 The typedef is a keyword used in C programming to provide some meaningful names
to the already existing variable in the C program. It behaves similarly as we define
the alias for the commands. In short, we can say that this keyword is used to redefine
the name of an already existing variable.

 Syntax of typedef
 typedef <existing_name> <alias_name>

 Till now, we have observed that the typedef keyword provides a nice shortcut by
providing an alternative name for an already existing variable. This keyword is useful
when we are dealing with the long data type especially, structure declarations.
Typedef in structure
typedef
 In C, typedef is considered as a storage class like other storage
classes (auto, register, static and extern),nevertheless the purpose
of typedef is to assign alternative names to existing types.

Output:
5 Compiler Error: multiple
storage classes in
declaration specifiers
Structures and functions
PASSING STRUCTURE TO FUNCTION IN C:
It can be done in below 3 ways.
 Passing structure to a function by value
 Passing structure to a function by address(reference)
 No need to pass a structure – Declare structure variable as global

1. Passing structure to a function by value


In this program, the whole structure is passed to another function by value. It
means the whole structure is passed to another function with all members and
their values. So, this structure can be accessed from called function. This concept
is very useful while writing very big programs in C.

Refer the program here structfun1.c


Structures and functions
2. PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:
 In this program, the whole structure is passed to another function by address.
It means only the address of the structure is passed to another function. The
whole structure is not passed to another function with all members and their
values. So, this structure can be accessed from called function by its address.

Refer the program here structfun2.c

3. DECLARING STRUCTURE VARIABLE AS GLOBAL IN C:


 Structure variables also can be declared as global variables as we declare
other variables in C. So, When a structure variable is declared as global, then it
is visible to all the functions in a program. In this scenario, we don’t need to
pass the structure to any function separately.

Refer the program here structfun3.c


Pointers to structures
C structure can be accessed in 2 ways in a C program. They are,
 Using normal structure variable
 Using pointer variable
Dot(.) operator is used to access the data using normal structure
variable and arrow (->) is used to access the data using pointer
variable.
structpointer.c

Refer programs here

structpointer.c
Self-referential Structures
 A self-referential C structure
is one which includes a pointer to
an “instance” of itself.
Self-referential Structures
Limitations of Structure
 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.
 No Data Hiding: C Structures do not permit data hiding. Structure
members can be accessed by any function, anywhere in the scope of the
Structure.
 Functions inside Structure: C structures do not permit functions inside
Structure.
 Static Members: C Structures cannot have static members inside their
body.
 Access Modifiers: C Programming language do not support access
modifiers. So they cannot be used in C Structures.
 Construction creation in Structure: Structures in C cannot have
constructor inside Structures.
Dedicated Initializer for Array
Dynamic Memory Allocation
 Dynamic Memory Allocation in C Programming Language - C
language provides features to manual management of memory, by using
this feature we can manage memory at run time, whenever we require
memory allocation or reallocation at run time by using Dynamic Memory
Allocation functions we can create amount of required memory.
 The functions are available in <stdlib.h>
 There are following functions:
 malloc - It is used to allocate specified number of bytes (memory blocks).
 calloc - It is used to allocate specified number of bytes (memory blocks)
and initialize all memory with 0.
 realloc - It is used to reallocate the dynamically allocated memory to
increase or decrease amount of the memory.
 free - It is used to release dynamically allocated memory.
Malloc()
 syntax of malloc
Ptr_var=(type_cast *)malloc(sizeof all elements)
Where ptr_var is the name of pointer that holds the starting address of allocated
memory block, type_cast is the data type into which the returned pointer (or
void type) is to be converted, and size specifies the size of allocated memory
block in bytes.
The pointer returned by malloc() is void *. It can be converted to any data type
as per the need of programmer.

Ex: int *ptr


ptr=(int *)malloc(10*sizeof(int))
After the execution of above statement, a consecutive memory block of 20 Bytes
(If size of integer is 2 Bytes) is allocated to the program. The address of the first
byte of the block is first casted into int and then assigned to the pointer ptr.
 Similarly for structure
Struct student
{
int roll;
Char name[30];
Float percentage;
};
Struct student *st_ptr;
Allocation of memory will be:
st_ptr=(struct student *)malloc (sizeof(struct sudent));
Calloc()
 Works exactly similar to malloc() function except the fact that it
needs two arguments as against one argument required by malloc().
 For ex:
int *ptr;
ptr=(int *) calloc(10,2)
Here, 2 specifies the size of data type in Bytes for which we want the
allocation to be made and 10 specify the number of elements for which
allocation is to be made.
 Minor difference is that memory allocated by malloc() function
contains garbage values, while memory allocated by calloc() function
contains all zeros.
Free()
 Used to deallocate the previously allocated memory using malloc() or
calloc() functions.

Syntax:
free (ptr_var);
Where ptr_var is the pointer in which the address of the allocated
memory block is assigned.
Realloc()
 The function is used to resize the size of memory block, which is
already allocated (i.e., to modify the size of already allocated memory
block).
 It is useful in two situations:
 If the allocated memory block is insufficient for current application.
 If the allocated memory is much more than what is required by the
current application. In other words it provides even more precise and
efficient utilization of memory.
 Syntax:
ptr_var= realloc(ptr_var,new_size)
Where ptr_var is the pointer holding the starting address of already
allocated memory block and new_size is the size in bytes you want the
system to allocate now.
Refer program here
realloc.txt

https://www.log2base2.com/C/pointer/realloc-in-c.h
Dynamic Array Creation
Union
 https://www.geeksforgeeks.org/union-c/
Similarities Between Structure and Union

 Both are user-defined data types used to store data of different types as a
single unit.
 Both structures and unions support only assignment = and sizeof operators.
The two structures or unions in the assignment must have the same members
and member types.
 A structure or a union can be passed by value to functions and returned by
value by functions. The argument must have the same type as the function
parameter. A structure or union is passed by value just like a scalar variable
as a corresponding parameter.
 ‘.’ operator or selection operator, which has one of the highest precedences,
is used for accessing member variables inside both the user-defined
datatypes.
Difference between structure and
Union
 https://www.geeksforgeeks.org/difference-structure-union-c/
Anonymous Structure and Union
 In C11 standard of C, anonymous Unions and structures were added. Anonymous unions/structures are also known as
unnamed unions/structures as they don’t have names. Since there is no names, direct objects(or variables) of them are not
created and we use them in nested structure or unions.
 Definition is just like that of a normal union just without a name or tag. For example,
 // Anonymous union example
union
{
char alpha;
int num;
};
 // Anonymous structure example
 struct
 {
 char alpha;
 int num;
 };
Abstract Data type (ADT) is a type (or class) for objects whose behavior
is defined by a set of values and a set of operations. The definition of
ADT only mentions what operations are to be performed but not how
these operations will be implemented. It does not specify how data will
be organized in memory and what algorithms will be used for
implementing the operations. It is called “abstract” because it gives an
implementation-independent view.

The process of providing only the essentials and hiding the details is
known as abstraction.
ADT

https://www.geeksforgeeks.org/abstract-data-types/

You might also like