Advanced Data types
in C
Structures
• Structures (also called structs) are a way to group several related
variables into one place. Each variable in the structure is known as
a member of the structure.
• You can create a structure by using the struct keyword and declare
each of its members inside curly braces:
Ok, so, how are structures useful?
• Imagine you have to write a program to store different information
about Cars, such as brand, model, and year. What's great about
structures is that you can create a single "Car template" and use it for
every cars you make. See below for a real life example.
Access Structure Members
To access members of a structure, use the dot syntax (.):
What About Strings
in Structures?
Copy Structures
Modify
Values
If you want to
change/modify a value, you
can use the dot syntax (.).
And to modify a string
value, the strcpy function is
useful again
Create a structure to store different information about Cars:
• An array of structures is a data structure in
programming where an array contains multiple
elements, and each element is a structure.
• A structure is a user-defined data type that
groups different types of data into a single unit.
Array of In an array of structures, each array element
holds a structure, which can hold different
Structure fields of different data types.
• Array: A collection of elements, all of the same
type, stored in contiguous memory locations.
• Structure: A user-defined data type that allows
you to combine data items of different kinds.
Array of structure
A union in C is a user-defined data type that
allows storing different data types in the same
memory location.
Unlike structures, where each member has its
own memory, all members of a union share the
Unions in C same memory location.
This means that at any given time, only one
member of the union can store a value, and the
size of a union is determined by the size of its
largest member.
Key Features of Unions:
Memory Sharing: All members of a union share the same memory
space, meaning only one member can hold a value at any time.
Size: The size of a union is equal to the size of its largest member,
because the entire union uses the largest member's space.
Use Case: Unions are useful when you need to store different types of
data but only one of them is needed at a time, which saves memory.
• In this example, the union Data has three members: i
(integer), f (float), and str (string).
Union • Only one member of the union can hold a value at any
given time,as they share the same memory space
Difference
between
structure
and union