SlideShare a Scribd company logo
Dynamic memory allocation
Dynamic memory allocation 
• Process of allocating memory at run time is 
known as dynamic memory allocation 
• Memory allocation functions:- 
– malloc :- allocates required size of bytes and returns a 
pointer to the first byte of allocated space 
– calloc:- allocates space for an array elements, 
initialises them and returns a pointer to the first byte 
of allocated space 
– free :- frees previously allocated space 
– realloc:- modifies the size of previously allocated 
space
malloc 
malloc function allocates a single block of memory of specified number of bytes at 
run time returning a void pointer type. Hence we can assign it to any datatype. 
General form 
Ptr = (cast-type *) malloc(byte-size) 
Example 
X = (int *) malloc(100 * sizeof(int)); /*allocates 100 * 2 bytes of memory space the 
start address assigned to pointer variable x */ 
cptr = (char*) malloc(10); // allocates 10 bytes of space 
st_var = (struct store*) malloc(10 * sizeof(struct store)); /* allocates space for 10 
structures of type store */ 
Dynamically allocated space has no predefined name and hence its contents can 
be accessed only through its pointer
A program using malloc 
/* an example program to illustrate use of variable length of array by using dynamic 
memory allocation function “malloc”*/ 
#include <stdlib.h> 
#include <stdio.h> 
#define NULL 0 
void main(){ 
int *arrptr,*arrptr1, num,i; // declare array pointer variable arptr 
clrscr(); 
printf("Enter the number of elements to be storedn”); 
scanf("%d",&num); 
arrptr = (int*)malloc( num * sizeof(int)); 
if(arrptr == NULL){ 
printf("sorry no space available in memoryn"); 
exit(1);} 
arrptr1=arrptr; 
for( i=0;i<num;i++) { // enter numbers into array of integer 
printf("n Enter number[%d] ",i); 
scanf( "%d",arrptr+i);} 
for( i=0;i<num;i++) // print numbers from array of integer 
printf( "n number[%d] is %d",i,*(arrptr1+i)); 
getch(); 
}
A program using malloc 
/* an example program to illustrate sum of variable length of arrays by using dynamic 
memory allocation function “malloc”*/ 
#include <stdlib.h> 
#include <stdio.h> 
void main(){ 
int *arr1,*arr2,num,*sum,i; // declare array pointer variable arptr 
Printf("Enter the number of elements to be storedn", num); 
scanf("%d",&num); 
arr1 = (int*)malloc( num * sizeof(int)); 
arr2 = (int*)malloc( num * sizeof(int)); 
sum = (int*)malloc( num * sizeof(int)); 
printf("n Enter values in 1st array”); 
for( i=0;i<num;i++) // enter numbers into array of integer 
scanf( "%d",arr1+i); 
printf("n Enter values in 2nd array"); 
for( i=0;i<num;i++) // enter numbers into array of integer 
scanf( "%d",arr2+i); 
Printf(“n the sum of two arrays:n”); 
for( i=0;i<num;i++) // sum and print numbers from array of integer 
{ *(sum+i)=*(arr1+i) + *(arr2+i); 
printf( “%d“,*(sum+i)); 
} 
}
calloc 
calloc function allocates a contiguous multiple blocks of memory of same size 
at run time. Useful for storing derived data types such as arrays and structure. 
All bytes are initialised to zero. 
General form 
ptr = (cast-type *) calloc(n, elem-size); // space for n blocks of size elem-size 
Example 
X = (record *) calloc(n, sizeof(record)); /*allocates n memory spaces of type 
record. the start address assigned to pointer variable x */ 
Dynamically allocated space has no predefined name and hence its 
contents can be accessed only through its pointer
A program using calloc 
/* an example program to illustrate use of variable length of array by using 
dynamic memory allocation function "calloc"*/ 
#include <stdlib.h> 
#include <stdio.h> 
#define NULL 0 
void main(){ 
char name[20], *arrptr,*arrptr1;// declare array pointer variable arptr 
int num,i; 
clrscr(); 
printf("Enter the number of elements to be storedn", &num); 
scanf("%d",&num); 
arrptr = (char *)calloc( num, sizeof(name)); 
if(arrptr == NULL){ 
printf("sorry no space available in memoryn"); 
exit(1);} 
arrptr1=arrptr; 
for( i=0;i<num;i++) { // enter names into array of chars 
printf("n Enter name[%d] ",i);scanf( "%s",arrptr+(i*sizeof(name)));} 
for( i=0;i<num;i++) // print names from array of chars 
printf( "n name[%d] is %s ",i,arrptr1+(i*sizeof(name))); 
getch(); 
}
free and realloc 
free 
Compile time storage is allocated and de-allocated by the system in 
accordance with its storage class. 
Dynamic allocation is done by the user after compilation at run time and hence 
it is the user’s responsibility to release the space when it is no more required. 
The function to release memory is : free(ptr); // ptr is the start of memory block 
returned by malloc or calloc 
realloc 
When the allocation by malloc or calloc requires to be increased or decreased 
then the modification can be done by function realloc:- 
ptr = realloc(ptr, newsize); // ptr is the original ptr returned by malloc 
for e.g. 
A=(char*) realloc(A,50);
Dynamic allocation of matrix 
/* program to dynamically create 2 dim arrays and Transposes the array */ 
#include <stdio.h> 
#include <stdlib.h> 
#include <conio.h> 
void main() 
{ 
int i,j,nrows,ncols; 
// declaring base pointer to pointer for arrays 
int** arrayA; 
int** arrayB; 
clrscr(); 
// Define the size of the array at run time 
printf("Enter number of rowsn"); 
scanf("%d",&nrows); 
printf("Enter number of columnsn"); 
scanf("%d",&ncols);
Dynamic allocation of matrix ( contd..) 
// -------arrayA--------------- 
// allocation of rows to arrayA 
arrayA=(int**)malloc(nrows*sizeof(int*)); 
// allocation of columns to arrayA 
for (i=0; i<nrows; i++) 
arrayA[i]=(int*)malloc(ncols*sizeof(int)); 
// ------arrayB----------------- 
// allocation of rows to arrayB 
arrayB=(int**)malloc(nrows*sizeof(int*)); 
// allocation of columns to arrayB 
for (i=0; i<nrows; i++) 
arrayB[i]=(int*)malloc(ncols*sizeof(int));
Dynamic allocation of matrix ( contd..) 
//Enter data into arrayA 
for (i=0; i<nrows; i++) 
{ 
printf("n Enter data for next row"); 
for (j=0; j<ncols; j++) 
{ 
printf("n enter data next column "); 
scanf("%d",&arrayA[i][j]); 
} 
} 
// Transpose arrayA data into arrayB 
for (i=0; i<nrows; i++) 
{ 
for (j=0; j<ncols; j++) 
{ 
arrayB[i][j] = arrayA[j][i]; 
} 
}
Dynamic allocation of matrix ( contd..) 
// printing arrayA 
printf("nn-------Array A------nn"); 
for (i=0; i<nrows; i++) 
{ 
printf("nn"); 
for (j=0; j<ncols; j++) 
{ 
printf("%5d",arrayA[i][j]); 
} 
} 
// printing arrayB 
printf("nn---Transposed Array A---nn"); 
for (i=0; i<nrows; i++) 
{ 
printf("nn"); 
for (j=0; j<ncols; j++) 
{ 
printf("%5d",arrayB[i][j]); 
} 
}
Dynamic allocation of matrix ( contd..) 
printf("nn"); 
getch(); 
// free allocated spaces 
for (i=0; i<nrows; i++) 
{ 
free((void*)arrayA[i]); 
free((void*)arrayA); 
free((void*)arrayB[i]); 
free((void*)arrayB); 
} 
}
Multiplication of Arrays 
/* program to dynamically create 2 dim arrays and Multiplies them into a third 
one*/ 
#include <stdio.h> 
#include <stdlib.h> 
#include <conio.h> 
void main() 
{ 
int i,j,k,nrows,ncols; 
// declaring base pointer to pointer for arrays 
int** arrayA; 
int** arrayB; 
int** arrayC; 
clrscr(); 
// Define the size of the array at run time 
printf("Enter number of rowsn"); 
scanf("%d",&nrows); 
printf("Enter number of columnsn"); 
scanf("%d",&ncols);
Multiplication of Arrays ( contd..) 
// -------arrayA--------------- 
// allocation of rows to arrayA 
arrayA=(int**)malloc(nrows*sizeof(int*)); 
// allocation of columns to arrayA 
for (i=0; i<nrows; i++) 
arrayA[i]=(int*)malloc(ncols*sizeof(int)); 
// ------arrayB----------------- 
// allocation of rows to arrayB 
arrayB=(int**)malloc(nrows*sizeof(int*)); 
// allocation of columns to arrayB 
for (i=0; i<nrows; i++) 
arrayB[i]=(int*)malloc(ncols*sizeof(int));
Multiplication of Arrays ( contd..) 
// ------arrayC----------------- 
// allocation of rows to arrayC 
arrayC=(int**)malloc(nrows*sizeof(int*)); 
// allocation of columns to arrayC 
for (i=0; i<nrows; i++) 
arrayC[i]=(int*)malloc(ncols*sizeof(int)); 
//Enter data into arrayA 
for (i=0; i<nrows; i++) 
{ 
printf("n Enter data for next row"); 
for (j=0; j<ncols; j++) 
{ 
printf("n enter data next column "); 
scanf("%d",&arrayA[i][j]); 
} 
}
Multiplication of Arrays ( contd..) 
// Transpose arrayA data into arrayB 
for (i=0; i<nrows; i++) 
{ 
for (j=0; j<ncols; j++) 
{ 
arrayB[i][j] = arrayA[j][i]; 
} 
} 
// Multiply arrayA with arrayB and store result data into arrayC 
for (i=0; i<nrows; i++) 
{ 
for (j=0; j<ncols; j++) 
{ 
arrayC[i][j] =0; 
for (k=0; k<ncols; k++) 
arrayC[i][j] += arrayA[i][k] * arrayB[k][j]; 
} 
}
Multiplication of Arrays ( contd..) 
/ printing arrayA 
printf("nn-------Array A------nn"); 
for (i=0; i<nrows; i++) 
{ 
printf("nn"); 
for (j=0; j<ncols; j++) 
{ 
printf("%5d",arrayA[i][j]); 
} 
} 
// printing arrayB 
printf("nn------Array B------nn"); 
for (i=0; i<nrows; i++) 
{ 
printf("nn"); 
for (j=0; j<ncols; j++) 
{ 
printf("%5d",arrayB[i][j]); 
} 
}
Multiplication of Arrays ( contd..) 
// printing arrayC 
printf("nn-----Result of Multiplication: Array C------nn"); 
for (i=0; i<nrows; i++) 
{ 
printf("nn"); 
for (j=0; j<ncols; j++) 
{ 
printf("%5d",arrayC[i][j]); 
} 
} 
printf("nn"); 
getch(); 
// free allocated spaces 
for (i=0; i<nrows; i++) 
{ 
free((void*)arrayA[i]); 
free((void*)arrayA); 
free((void*)arrayB[i]); 
free((void*)arrayB); 
free((void*)arrayC[i]); 
free((void*)arrayC); 
} 
}

More Related Content

What's hot

C pointer
C pointerC pointer
Pointer in c
Pointer in cPointer in c
Pointer in c
lavanya marichamy
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
Faisal Shahzad Khan
 
Array in c++
Array in c++Array in c++
Array in c++
Mahesha Mano
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
Md. Afif Al Mamun
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
Grishma Rajput
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
Vijayananda Ratnam Ch
 
Introduction to array and string
Introduction to array and stringIntroduction to array and string
Introduction to array and string
MuntasirMuhit
 
Pointer in C
Pointer in CPointer in C
Pointer in C
bipchulabmki
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
Munazza-Mah-Jabeen
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 
File handling-c
File handling-cFile handling-c
Malloc() and calloc() in c
Malloc() and calloc() in cMalloc() and calloc() in c
Malloc() and calloc() in c
Mahesh Tibrewal
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
Arpita Patel
 
String in c
String in cString in c
String in c
Suneel Dogra
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
Muhammed Thanveer M
 
Manipulation strings in c++
Manipulation strings in c++Manipulation strings in c++
Manipulation strings in c++
SeethaDinesh
 

What's hot (20)

C pointer
C pointerC pointer
C pointer
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
 
Array in c++
Array in c++Array in c++
Array in c++
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Introduction to array and string
Introduction to array and stringIntroduction to array and string
Introduction to array and string
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Malloc() and calloc() in c
Malloc() and calloc() in cMalloc() and calloc() in c
Malloc() and calloc() in c
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
String in c
String in cString in c
String in c
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
Manipulation strings in c++
Manipulation strings in c++Manipulation strings in c++
Manipulation strings in c++
 

Similar to Dynamic memory allocation

Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
Srikanth
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
Srikanth
 
Dynamic allocation
Dynamic allocationDynamic allocation
Dynamic allocation
CGC Technical campus,Mohali
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Mohammad Usman
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
ngonidzashemutsipa
 
Unit3 C
Unit3 C Unit3 C
Unit3 C
arnold 7490
 
Pointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptxPointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptx
krishna50blogging
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
rushabhshah600
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
Rabin BK
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
VeerannaKotagi1
 
06 -working_with_strings
06  -working_with_strings06  -working_with_strings
06 -working_with_strings
Hector Garzo
 
Input output functions
Input output functionsInput output functions
Input output functions
hyderali123
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
AkhilaaReddy
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
웅식 전
 
#include stdio.h#include stdlib.h#include string.h#inclu.pdf
#include stdio.h#include stdlib.h#include string.h#inclu.pdf#include stdio.h#include stdlib.h#include string.h#inclu.pdf
#include stdio.h#include stdlib.h#include string.h#inclu.pdf
apleather
 
Arrays
ArraysArrays
Arrays
AnaraAlam
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
Adamq0DJonese
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
YOGESH SINGH
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
kirthika jeyenth
 

Similar to Dynamic memory allocation (20)

Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
Dynamic allocation
Dynamic allocationDynamic allocation
Dynamic allocation
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
Unit3 C
Unit3 C Unit3 C
Unit3 C
 
Pointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptxPointers and Memory Allocation ESC101.pptx
Pointers and Memory Allocation ESC101.pptx
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
06 -working_with_strings
06  -working_with_strings06  -working_with_strings
06 -working_with_strings
 
Input output functions
Input output functionsInput output functions
Input output functions
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
 
#include stdio.h#include stdlib.h#include string.h#inclu.pdf
#include stdio.h#include stdlib.h#include string.h#inclu.pdf#include stdio.h#include stdlib.h#include string.h#inclu.pdf
#include stdio.h#include stdlib.h#include string.h#inclu.pdf
 
Arrays
ArraysArrays
Arrays
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
 

More from Naveen Gupta

Reproduction
ReproductionReproduction
Reproduction
Naveen Gupta
 
stem cells
stem cellsstem cells
stem cells
Naveen Gupta
 
Mitosis2
Mitosis2Mitosis2
Mitosis2
Naveen Gupta
 
Mestrual cycle
Mestrual cycleMestrual cycle
Mestrual cycle
Naveen Gupta
 
Menstrual cycle 2
Menstrual cycle 2Menstrual cycle 2
Menstrual cycle 2
Naveen Gupta
 
Lecture 1 family planning
Lecture 1 family planningLecture 1 family planning
Lecture 1 family planningNaveen Gupta
 
Human reproduction
Human reproductionHuman reproduction
Human reproduction
Naveen Gupta
 
Genetic engineering
Genetic engineeringGenetic engineering
Genetic engineering
Naveen Gupta
 
sequencing of genome
sequencing of genomesequencing of genome
sequencing of genome
Naveen Gupta
 
Cell reproduction mitosis&meosis
Cell reproduction mitosis&meosisCell reproduction mitosis&meosis
Cell reproduction mitosis&meosis
Naveen Gupta
 
Cell respiration
Cell respirationCell respiration
Cell respiration
Naveen Gupta
 
Asexual and sexual_reproduction
Asexual and sexual_reproductionAsexual and sexual_reproduction
Asexual and sexual_reproduction
Naveen Gupta
 
Biotechnology and genetic engineering
Biotechnology and genetic engineeringBiotechnology and genetic engineering
Biotechnology and genetic engineeringNaveen Gupta
 

More from Naveen Gupta (13)

Reproduction
ReproductionReproduction
Reproduction
 
stem cells
stem cellsstem cells
stem cells
 
Mitosis2
Mitosis2Mitosis2
Mitosis2
 
Mestrual cycle
Mestrual cycleMestrual cycle
Mestrual cycle
 
Menstrual cycle 2
Menstrual cycle 2Menstrual cycle 2
Menstrual cycle 2
 
Lecture 1 family planning
Lecture 1 family planningLecture 1 family planning
Lecture 1 family planning
 
Human reproduction
Human reproductionHuman reproduction
Human reproduction
 
Genetic engineering
Genetic engineeringGenetic engineering
Genetic engineering
 
sequencing of genome
sequencing of genomesequencing of genome
sequencing of genome
 
Cell reproduction mitosis&meosis
Cell reproduction mitosis&meosisCell reproduction mitosis&meosis
Cell reproduction mitosis&meosis
 
Cell respiration
Cell respirationCell respiration
Cell respiration
 
Asexual and sexual_reproduction
Asexual and sexual_reproductionAsexual and sexual_reproduction
Asexual and sexual_reproduction
 
Biotechnology and genetic engineering
Biotechnology and genetic engineeringBiotechnology and genetic engineering
Biotechnology and genetic engineering
 

Recently uploaded

Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
JomonJoseph58
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
giancarloi8888
 
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDFLifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Vivekanand Anglo Vedic Academy
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
RamseyBerglund
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
nitinpv4ai
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.pptLevel 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Henry Hollis
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
zuzanka
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
National Information Standards Organization (NISO)
 

Recently uploaded (20)

Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
 
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDFLifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.pptLevel 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
 

Dynamic memory allocation

  • 2. Dynamic memory allocation • Process of allocating memory at run time is known as dynamic memory allocation • Memory allocation functions:- – malloc :- allocates required size of bytes and returns a pointer to the first byte of allocated space – calloc:- allocates space for an array elements, initialises them and returns a pointer to the first byte of allocated space – free :- frees previously allocated space – realloc:- modifies the size of previously allocated space
  • 3. malloc malloc function allocates a single block of memory of specified number of bytes at run time returning a void pointer type. Hence we can assign it to any datatype. General form Ptr = (cast-type *) malloc(byte-size) Example X = (int *) malloc(100 * sizeof(int)); /*allocates 100 * 2 bytes of memory space the start address assigned to pointer variable x */ cptr = (char*) malloc(10); // allocates 10 bytes of space st_var = (struct store*) malloc(10 * sizeof(struct store)); /* allocates space for 10 structures of type store */ Dynamically allocated space has no predefined name and hence its contents can be accessed only through its pointer
  • 4. A program using malloc /* an example program to illustrate use of variable length of array by using dynamic memory allocation function “malloc”*/ #include <stdlib.h> #include <stdio.h> #define NULL 0 void main(){ int *arrptr,*arrptr1, num,i; // declare array pointer variable arptr clrscr(); printf("Enter the number of elements to be storedn”); scanf("%d",&num); arrptr = (int*)malloc( num * sizeof(int)); if(arrptr == NULL){ printf("sorry no space available in memoryn"); exit(1);} arrptr1=arrptr; for( i=0;i<num;i++) { // enter numbers into array of integer printf("n Enter number[%d] ",i); scanf( "%d",arrptr+i);} for( i=0;i<num;i++) // print numbers from array of integer printf( "n number[%d] is %d",i,*(arrptr1+i)); getch(); }
  • 5. A program using malloc /* an example program to illustrate sum of variable length of arrays by using dynamic memory allocation function “malloc”*/ #include <stdlib.h> #include <stdio.h> void main(){ int *arr1,*arr2,num,*sum,i; // declare array pointer variable arptr Printf("Enter the number of elements to be storedn", num); scanf("%d",&num); arr1 = (int*)malloc( num * sizeof(int)); arr2 = (int*)malloc( num * sizeof(int)); sum = (int*)malloc( num * sizeof(int)); printf("n Enter values in 1st array”); for( i=0;i<num;i++) // enter numbers into array of integer scanf( "%d",arr1+i); printf("n Enter values in 2nd array"); for( i=0;i<num;i++) // enter numbers into array of integer scanf( "%d",arr2+i); Printf(“n the sum of two arrays:n”); for( i=0;i<num;i++) // sum and print numbers from array of integer { *(sum+i)=*(arr1+i) + *(arr2+i); printf( “%d“,*(sum+i)); } }
  • 6. calloc calloc function allocates a contiguous multiple blocks of memory of same size at run time. Useful for storing derived data types such as arrays and structure. All bytes are initialised to zero. General form ptr = (cast-type *) calloc(n, elem-size); // space for n blocks of size elem-size Example X = (record *) calloc(n, sizeof(record)); /*allocates n memory spaces of type record. the start address assigned to pointer variable x */ Dynamically allocated space has no predefined name and hence its contents can be accessed only through its pointer
  • 7. A program using calloc /* an example program to illustrate use of variable length of array by using dynamic memory allocation function "calloc"*/ #include <stdlib.h> #include <stdio.h> #define NULL 0 void main(){ char name[20], *arrptr,*arrptr1;// declare array pointer variable arptr int num,i; clrscr(); printf("Enter the number of elements to be storedn", &num); scanf("%d",&num); arrptr = (char *)calloc( num, sizeof(name)); if(arrptr == NULL){ printf("sorry no space available in memoryn"); exit(1);} arrptr1=arrptr; for( i=0;i<num;i++) { // enter names into array of chars printf("n Enter name[%d] ",i);scanf( "%s",arrptr+(i*sizeof(name)));} for( i=0;i<num;i++) // print names from array of chars printf( "n name[%d] is %s ",i,arrptr1+(i*sizeof(name))); getch(); }
  • 8. free and realloc free Compile time storage is allocated and de-allocated by the system in accordance with its storage class. Dynamic allocation is done by the user after compilation at run time and hence it is the user’s responsibility to release the space when it is no more required. The function to release memory is : free(ptr); // ptr is the start of memory block returned by malloc or calloc realloc When the allocation by malloc or calloc requires to be increased or decreased then the modification can be done by function realloc:- ptr = realloc(ptr, newsize); // ptr is the original ptr returned by malloc for e.g. A=(char*) realloc(A,50);
  • 9. Dynamic allocation of matrix /* program to dynamically create 2 dim arrays and Transposes the array */ #include <stdio.h> #include <stdlib.h> #include <conio.h> void main() { int i,j,nrows,ncols; // declaring base pointer to pointer for arrays int** arrayA; int** arrayB; clrscr(); // Define the size of the array at run time printf("Enter number of rowsn"); scanf("%d",&nrows); printf("Enter number of columnsn"); scanf("%d",&ncols);
  • 10. Dynamic allocation of matrix ( contd..) // -------arrayA--------------- // allocation of rows to arrayA arrayA=(int**)malloc(nrows*sizeof(int*)); // allocation of columns to arrayA for (i=0; i<nrows; i++) arrayA[i]=(int*)malloc(ncols*sizeof(int)); // ------arrayB----------------- // allocation of rows to arrayB arrayB=(int**)malloc(nrows*sizeof(int*)); // allocation of columns to arrayB for (i=0; i<nrows; i++) arrayB[i]=(int*)malloc(ncols*sizeof(int));
  • 11. Dynamic allocation of matrix ( contd..) //Enter data into arrayA for (i=0; i<nrows; i++) { printf("n Enter data for next row"); for (j=0; j<ncols; j++) { printf("n enter data next column "); scanf("%d",&arrayA[i][j]); } } // Transpose arrayA data into arrayB for (i=0; i<nrows; i++) { for (j=0; j<ncols; j++) { arrayB[i][j] = arrayA[j][i]; } }
  • 12. Dynamic allocation of matrix ( contd..) // printing arrayA printf("nn-------Array A------nn"); for (i=0; i<nrows; i++) { printf("nn"); for (j=0; j<ncols; j++) { printf("%5d",arrayA[i][j]); } } // printing arrayB printf("nn---Transposed Array A---nn"); for (i=0; i<nrows; i++) { printf("nn"); for (j=0; j<ncols; j++) { printf("%5d",arrayB[i][j]); } }
  • 13. Dynamic allocation of matrix ( contd..) printf("nn"); getch(); // free allocated spaces for (i=0; i<nrows; i++) { free((void*)arrayA[i]); free((void*)arrayA); free((void*)arrayB[i]); free((void*)arrayB); } }
  • 14. Multiplication of Arrays /* program to dynamically create 2 dim arrays and Multiplies them into a third one*/ #include <stdio.h> #include <stdlib.h> #include <conio.h> void main() { int i,j,k,nrows,ncols; // declaring base pointer to pointer for arrays int** arrayA; int** arrayB; int** arrayC; clrscr(); // Define the size of the array at run time printf("Enter number of rowsn"); scanf("%d",&nrows); printf("Enter number of columnsn"); scanf("%d",&ncols);
  • 15. Multiplication of Arrays ( contd..) // -------arrayA--------------- // allocation of rows to arrayA arrayA=(int**)malloc(nrows*sizeof(int*)); // allocation of columns to arrayA for (i=0; i<nrows; i++) arrayA[i]=(int*)malloc(ncols*sizeof(int)); // ------arrayB----------------- // allocation of rows to arrayB arrayB=(int**)malloc(nrows*sizeof(int*)); // allocation of columns to arrayB for (i=0; i<nrows; i++) arrayB[i]=(int*)malloc(ncols*sizeof(int));
  • 16. Multiplication of Arrays ( contd..) // ------arrayC----------------- // allocation of rows to arrayC arrayC=(int**)malloc(nrows*sizeof(int*)); // allocation of columns to arrayC for (i=0; i<nrows; i++) arrayC[i]=(int*)malloc(ncols*sizeof(int)); //Enter data into arrayA for (i=0; i<nrows; i++) { printf("n Enter data for next row"); for (j=0; j<ncols; j++) { printf("n enter data next column "); scanf("%d",&arrayA[i][j]); } }
  • 17. Multiplication of Arrays ( contd..) // Transpose arrayA data into arrayB for (i=0; i<nrows; i++) { for (j=0; j<ncols; j++) { arrayB[i][j] = arrayA[j][i]; } } // Multiply arrayA with arrayB and store result data into arrayC for (i=0; i<nrows; i++) { for (j=0; j<ncols; j++) { arrayC[i][j] =0; for (k=0; k<ncols; k++) arrayC[i][j] += arrayA[i][k] * arrayB[k][j]; } }
  • 18. Multiplication of Arrays ( contd..) / printing arrayA printf("nn-------Array A------nn"); for (i=0; i<nrows; i++) { printf("nn"); for (j=0; j<ncols; j++) { printf("%5d",arrayA[i][j]); } } // printing arrayB printf("nn------Array B------nn"); for (i=0; i<nrows; i++) { printf("nn"); for (j=0; j<ncols; j++) { printf("%5d",arrayB[i][j]); } }
  • 19. Multiplication of Arrays ( contd..) // printing arrayC printf("nn-----Result of Multiplication: Array C------nn"); for (i=0; i<nrows; i++) { printf("nn"); for (j=0; j<ncols; j++) { printf("%5d",arrayC[i][j]); } } printf("nn"); getch(); // free allocated spaces for (i=0; i<nrows; i++) { free((void*)arrayA[i]); free((void*)arrayA); free((void*)arrayB[i]); free((void*)arrayB); free((void*)arrayC[i]); free((void*)arrayC); } }