Unit-5 C Pro
Unit-5 C Pro
2. Automatic Allocation
void func() {
int a = 5; // automatic allocation
auto int b = 10; // same as above
}
3. Dynamic Allocation
Page1
Structures and Unions
Four main functions used:
malloc()
calloc()
realloc()
free()
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int *)malloc(5 * sizeof(int)); // Allocate memory for 5 integers
free(ptr);
return 0;
}
2. calloc() – Contiguous Allocation
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
Page2
Structures and Unions
ptr = (int *)calloc(5, sizeof(int)); // Allocate and zero-initialize 5 integers
free(ptr);
return 0;
}
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int *)malloc(3 * sizeof(int));
ptr[3] = 4;
ptr[4] = 5;
free(ptr);
return 0;
}
Used to deallocate memory that was previously allocated using malloc(), calloc(), or
realloc().
Frees up space from the heap, preventing memory leaks.
Syntax:
Page3
Structures and Unions
free(ptr);
Example:
if(ptr == NULL) {
printf("Memory not allocated!\n");
}
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.
Page4
Structures and Unions
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 total mark;
};
Thus, the stud1 and stud2 are structure variables of type student. The above structure
can hold information of 2 students.
Struct structure_name
{
typeelement1;
typeelement2;
……………..
Type elementn;
}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;
Output
STUDENTSDETAILS:
Rollnumber:1
Name:Venkat
Total Marks:98.000000
Rollnumber:2
Page6
Structures and Unions
Name: Arpita
Total Marks:99.000000
Rollnumber:3
Name:Shweta
TotalMarks:99.000000
#include <stdio.h>
// Define structure with typedef
typedef struct {
int id;
char name[20];
} Student;
int main() {
Student s1; // No need to use 'struct' keyword
s1.id = 101;
snprintf(s1.name, sizeof(s1.name), "Alice");
return 0;
}
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.
struct struct_name
{
Type element1;
typeelement2;
……………..
Page7
Structures and Unions
Type elementn;
}array name[size];
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("STUDENTSDETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRollnumber:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Totalmark:%d\n",stud[i].totalmark);
}
Page8
Structures and Unions
getch();
}
OUTPUT
Enter total numberofstudents: 3
Enterdetailsof1 student
Name:SUBAHAS
Rollnumber:11
Total mark:589
Enterdetailsof2 student
Name:RUKSANA
Rollnumber:12
Total mark:594
Enterdetailsof3 student
Name:SANA
Rollnumber:13
Total mark:595
STUDENTSDETAILS:
Roll number:11
Name:SUBAHAS
Total mark:589
Roll number:12
Name:RUKSANA
Total mark:594
Rollnumber:13
Name: SANA
Totalmark:595
Declaration of the embedded structure must appear before the declaration of the outer
structure. For example
#include <stdio.h>
#include <conio.h>
void main()
{
Page9
Structures and Unions
structdob
{
int
day;intmo
nth; int
year;
};
struct student
{
Struct dobd;
int rollno;
charname[25];
int totalmark;
}stud[25];
int n,i;
clrscr();
printf("Entertotalnumberofstudents");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnterdetailsof%dstudent",i+1);
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("\nSTUDENTSDETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRollnumber:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Totalmark:%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();
}
Page10
Structures and Unions
OUTPUT
Enter total number ofstudents2
Enterdetailsof2student Name:
sarita
Rollnumber:18
Total mark:598
Dateofbirth(Format:0106 2010):121997
STUDENTSDETAILS:
Rollnumber:12
Name: karthik
Totalmark:588
Dateofbirth:11/12/1997
Rollnumber:18
Name: sarita
Totalmark:598
Dateofbirth:1/2/1997
Only specific fields (members) of a structure are passed to the function, like passing individual
variables.
Example:
#include <stdio.h>
struct Student {
int roll;
float marks;
};
int main() {
struct Student s1 = {101, 87.5};
display(s1.roll, s1.marks); // passing individual members
return 0;
}
Key Points:
You can pass the whole structure to a function by value (copy) or by reference (pointer).
struct Student {
int roll;
float marks;
};
int main() {
struct Student s1 = {102, 92.0};
display(s1); // passing entire structure
return 0;
}
Simple Example:
#include <stdio.h>
// Define a structure
struct Student {
int roll;
float marks;
};
Page12
Structures and Unions
int main() {
struct Student s1 = {101, 88.5};
return 0;
}
Key Points:
Union
Union is a user created data type similar to structure but in this case all the members
share a common memory location. The size of the union corresponds to the length of the
largest member. Since the member share a common location they have the same starting
address.
Page13
Structures and Unions
……………..
type elementn;
};
For example, the following code declares a union datatype 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 element1;
type element2;
……………..
type elementn;
}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;
Page14
Structures and Unions
Structure Union
The amount of memory required to store a The amount of memory required is always equal
structure variable is the sum of the size of all the to that required by its largest member.
members.
Each member have their own memory space. One block is used by all the member of the union.
Within a structure all members gets memory While retrieving data from a union the type
allocated; therefore any member can be that is being retrieved must be the type most
retrieved at any time. recently stored. It is the programmer's
responsibility to keep track of which type is
currently stored in a union; the results are
implementation-dependent if something is
stored as one type and extracted as another.
One or more members of a structure can be A union may only be initialized with a value
initialized at once. of the type of its first member; thus union u
described above (during example
declaration) can only be initialized with an
integer value.
Page15
Structures and Unions
Key Points:
Syntax:
enum enum_name {
value1, // default is 0
value2, // default is 1
value3 // and so on...
};
enum enum_name {
value1 = 10,
value2 = 20,
value3 = 30
};
Example 1 :
#include <stdio.h>
int main() {
enum Day today;
today = WEDNESDAY;
return 0;
}
Page16