unit 5
unit 5
Question
No
1 What is structure? Write the syntax for structure.
A structure in C is a user-defined data type that allows grouping variables of different types under a
single name. Structures are used to represent complex data types, similar to records in other program
languages.
They are particularly useful for grouping related data, such as attributes of a person (name, age, etc.)
student (roll number, marks, etc.).
struct Student
{
char name[50]; // character array to hold student's name
int roll_no; // integer to hold roll number
float marks; // float to hold marks
};
Dynamic memory allocation refers to the process of allocating memory during the execution of a
program, rather than at compile time. This allows a program to request memory as needed and to
release it when it is no longer needed, offering flexibility in managing memory based on runtime
conditions.
In C, dynamic memory allocation is done using functions defined in the <stdlib.h> library,
specifically:
● malloc()
● calloc()
● realloc()
● free()
● Dot Operator (.): Used when you have a structure variable (non-pointer).
● Arrow Operator (->): Used when you have a pointer to a structure
Syntax:
struct StructureName arrayName[size];
Structure Array
A structure is a user-defined data type that
allows grouping together different types of An array is a collection of variables of the
data elements (variables). Each element in a same data type. All elements in an array are of
structure is called a member, and each member the same type and are stored in contiguous
can have a different data type. memory locations.
Structures are used when you need to group Arrays are used when you need to store
different types of data together to represent an multiple values of the same type, such as a
entity (like a student with name, age, and collection of integers, floats, or characters.
marks).
struct StructureName { data_type array_name[size];
data_type member1;
data_type member2;
// More members
};
This structure is anonymous (i.e., it doesn’t have a name) and contains two members:
struct ID_Card {
char name[50]; // Student's name (string)
int roll_number; // Roll number of the student (integer)
char course[50]; // Course the student is enrolled in (string)
char dob[15]; // Date of birth in string format (e.g., DD/MM/YYYY)
};
int main() {
// Declare and initialize a structure variable for a student
struct ID_Card student1 = {
"John Doe", // Name
101, // Roll number
"Computer Science",// Course
"15/03/2001" // Date of birth
};