[go: up one dir, main page]

0% found this document useful (0 votes)
3 views16 pages

Unit-5 C Pro

The document explains memory allocation in C, detailing static, automatic, and dynamic allocation, along with examples for each type. It also covers structures, their declaration, initialization, and usage, including arrays of structures and embedded structures. Additionally, it discusses best practices for memory management and how to pass structures to functions.

Uploaded by

Arun
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)
3 views16 pages

Unit-5 C Pro

The document explains memory allocation in C, detailing static, automatic, and dynamic allocation, along with examples for each type. It also covers structures, their declaration, initialization, and usage, including arrays of structures and embedded structures. Additionally, it discusses best practices for memory management and how to pass structures to functions.

Uploaded by

Arun
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/ 16

Structures and Unions

Explanation of Static Allocation, Dynamic Allocation, and Automatic


Allocation in C:
1. Static Allocation

 Memory is allocated at compile time.


 Uses global, static, and local non-dynamic variables.
 Memory is fixed and cannot be changed during program execution.
 Memory stays reserved throughout the program's lifetime.
 Variables are stored in the data segment of memory.
 Example:

int x = 10; // static allocation


static int y = 20; // also static

2. Automatic Allocation

 Memory is allocated automatically when a function is called.


 It is used for local variables inside functions (non-static).
 Memory is freed automatically when the function ends.
 Stored in the stack segment.
 The keyword auto exists, but is rarely used since it's default.
 Example:

void func() {
int a = 5; // automatic allocation
auto int b = 10; // same as above
}

3. Dynamic Allocation

 Memory is allocated at runtime, using functions from <stdlib.h>.


 Uses malloc(), calloc(), realloc(), and free().
 Memory is allocated on the heap segment.
 More flexible: allows you to allocate memory based on input or logic.
 You must manually free the memory using free() to avoid memory leaks.
 Example:

int *ptr = (int *)malloc(sizeof(int) * 5); // dynamic


allocation
free(ptr); // freeing memory

Dynamic Memory Allocation in C


 Used to allocate memory at runtime from the heap.
 Enables creation of flexible data structures like linked lists, trees, etc.
 Declared in the header file: #include <stdlib.h>

Page1
Structures and Unions
 Four main functions used:

 malloc()
 calloc()
 realloc()
 free()

1. malloc() – Memory Allocation

 Allocates a single block of memory of a given size.


 Returns a pointer to the first byte of allocated memory.
 Memory is not initialized (contains garbage values).
 Syntax:

ptr = (castType *) malloc(size_in_bytes);

 Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;
ptr = (int *)malloc(5 * sizeof(int)); // Allocate memory for 5 integers

for(int i = 0; i < 5; i++)


ptr[i] = i + 1;

for(int i = 0; i < 5; i++)


printf("%d ", ptr[i]);

free(ptr);
return 0;
}
2. calloc() – Contiguous Allocation

 Allocates multiple blocks of memory, each of the same size.


 Initializes all blocks to zero.
 Syntax:

ptr = (castType *) calloc(number_of_blocks, size_of_each_block);

 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

for(int i = 0; i < 5; i++)


printf("%d ", ptr[i]); // Output will be 0 0 0 0 0

free(ptr);
return 0;
}

3. realloc() – Reallocate Memory

 Used to resize previously allocated memory.


 Can increase or decrease memory size.
 Syntax:

ptr = (castType *) realloc(ptr, new_size);

 Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;
ptr = (int *)malloc(3 * sizeof(int));

for(int i = 0; i < 3; i++)


ptr[i] = i + 1;

ptr = (int *)realloc(ptr, 5 * sizeof(int)); // Resize to hold 5 integers

ptr[3] = 4;
ptr[4] = 5;

for(int i = 0; i < 5; i++)


printf("%d ", ptr[i]);

free(ptr);
return 0;
}

4. free() – Free Allocated Memory

 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:

int *ptr = (int *)malloc(10 * sizeof(int));


// use the memory
free(ptr); // release it when done
Best Practices:

 Always check if memory allocation is successful:

if(ptr == NULL) {
printf("Memory not allocated!\n");
}

 Always free dynamically allocated memory when it’s no longer needed.


 Avoid using freed pointers (dangling pointers).

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 element1;
Type element2;
……………..
Type elementn;
};
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.

We can declare structure variables as follows


struct structure_namevar1,var2,…..,varn;
Example:
To store the names, roll number and total mark of a student you can declare 3

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;
};

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
{
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;

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.
Page5
Structures and Unions
Example:
In the above example stud1 is a structure variable of type student. To access the
member name, we would writestud1.name. Similarly, stud1’s rollno and stud1’s totalmark
can be accessed by writing stud1.rollno andstud1.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_namevar={val1,val2,val3…..};
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
structstudent
{
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(“STUDENTSDETAILS:\n”);
printf(“\n\nRollnumber:%d\nName:%s\nTotalMarks:%f”,stud1.rollno,stud1.name,stud1.total
mark);
printf(“\n\nRollnumber:%d\nName:%s\nTotalMarks:%f”,stud2.rollno,stud2.name,stud2.total
mark);
printf(“\n\nRollnumber:%d\nName:%s\nTotalMarks:%f”,stud3.rollno,stud3.name,stud3.total
mark);
getch();
}

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

Use typedef with struct?


 In C, defining a struct requires repeating the struct keyword.
 typedef gives a custom name (alias) to the struct, making code cleaner and easier to use.

#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");

printf("ID: %d\n", s1.id);


printf("Name: %s\n", s1.name);

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.

The declaration statement is given below.

struct struct_name
{
Type element1;
typeelement2;
……………..

Page7
Structures and Unions
Type elementn;
}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.

Program to demonstrate use of array of structure


#include <stdio.h>
#include <conio.h>
void main()
{
struct student
{
introllno;
charname[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("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

Structure as structure member(Embeddedstructure):


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
membertoitselfwhenastructureisusedasstructuremember.Insuchsituation,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()
{

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

Enter details of1student


Name: karthik
Rollnumber:12
Total mark:588
Dateofbirth(Format:0106 2010):11121997

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

STRUCTURE AND FUNCTIONS

1) Passing Structure Members to Functions

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;
};

void display(int r, float m) {


Page11
Structures and Unions
printf("Roll: %d\n", r);
printf("Marks: %.2f\n", m);
}

int main() {
struct Student s1 = {101, 87.5};
display(s1.roll, s1.marks); // passing individual members
return 0;
}
Key Points:

 Simple and efficient for small data.


 Can’t access other members inside the function.

2) Passing Entire Structure to Function

You can pass the whole structure to a function by value (copy) or by reference (pointer).

Example 1: Passing by Value (Copy)


#include <stdio.h>

struct Student {
int roll;
float marks;
};

void display(struct Student s) {


printf("Roll: %d\n", s.roll);
printf("Marks: %.2f\n", s.marks);
}

int main() {
struct Student s1 = {102, 92.0};
display(s1); // passing entire structure
return 0;
}

Structures and Pointers in C


You can use pointers to structures to:

 Access structure members using -> (arrow operator)


 Pass structures to functions efficiently

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};

// Declare a pointer to the structure


struct Student *ptr;

// Point to the address of s1


ptr = &s1;

// Access members using pointer


printf("Roll = %d\n", ptr->roll);
printf("Marks = %.2f\n", ptr->marks);

// You can also modify the structure using pointer


ptr->marks = 90.0;
printf("Updated Marks = %.2f\n", s1.marks);

return 0;
}

Key Points:

 struct Student *ptr; → declares a pointer to struct Student


 ptr = &s1; → assigns address of s1 to pointer
 ptr->roll or (*ptr).roll → both access the roll field

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.

The real purpose of unions is to prevent memory fragmentation by arranging for a


standard size for data in the memory. By having a standard data size we can guarantee that
any hole left when dynamically allocated memory is freed will always be reusable by
another instance of the same type of union. This is a natural strategy in system
programming where many instances of different kinds of variables with a related purpose
and stored dynamically.
A union is declared in the same way as a structure.The syntax of union declaration is
union union_name
{
type element1;
type element2;

Page13
Structures and Unions
……………..
type elementn;
};

This declares a type template.Variables are the n declared as:


union union_name x,y,z;

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

Compare structure and Union


The difference between structure and union is,

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.

Keyword struct defines a structure Keyword union defines a union.


struct s_tag Union u_tag
{ {
int ival; int ival;
float fval; float fval;
char*cptr; char*cptr;
}s; }u;

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.

Enumerated Data Type in C (enum)


Definition:

 enum (short for enumeration) is a user-defined data type.


 It is used to assign names to integral constants.
 Makes programs more readable and maintainable.

Page15
Structures and Unions
Key Points:

1. Declared using the enum keyword.


2. The default value of the first enumerator is 0, second is 1, and so on.
3. You can manually assign custom integer values.
4. Enumerated values are basically integers behind the scenes.
5. Useful in switch and if conditions to improve readability.

Syntax:
enum enum_name {
value1, // default is 0
value2, // default is 1
value3 // and so on...
};

Or with custom values:

enum enum_name {
value1 = 10,
value2 = 20,
value3 = 30
};

Example 1 :
#include <stdio.h>

enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};

int main() {
enum Day today;

today = WEDNESDAY;

printf("Today is day number: %d\n", today); // Output: 3

return 0;
}

Page16

You might also like