SlideShare une entreprise Scribd logo
1  sur  31
INPUT-OUTPUT FUNCTION
INTRODUCTION Reading, writing & processing are the 3 essential function Inputting data 2 types               assignment (a==5)               Through functions(scanf(),getchar() etc) Output         only functions (printf(),putchar()..etc Header file for input & output functions           #include<stdio.h>
Reading a chara using getchar getchar() read one chara at a time Syntax         variable name=getchar(); Wait until the key is pressed,then value inputted will assigned to the variable Example     name= getchar();
program #include<stdio.h> main() { char answer; Printf(“would you like to know my name?”); Printf(“Type Y for yes & N for no”); answer=getchar(); If(answer==Y !! answer== y) Printf(“my name is busy bee”); else printf(“you are good for nothing”); }
Successively read character ------- ------ char character; character=‘ ‘ while(character!= ‘’) {   character=getchar(); } ------ ------
gets Format        #include<stdio.h>        char*gets(char*str); Read character from the input and places in array pointed by the string Read until EOF(End off File) or “” is generated  Reading successfully *str return  Failure return NULL  No limit of no of characters
program #include< stdio.h> #include<stdlib.h> Int main void() { FILE *fp; Char fname[128]; Printf(“enter the filename”); gets(filename); If((fp=fopen(fname,”r”))==NULL){ Printf(“cannot open the file”); exit(1); } fclose(fp); Return0; }
printf Format     #include<stdio.h> intprintf(const char*format,…..); Write stdoutarg Format consist 2 item       character        the way the arg defined
Cont………. Printf(“Hi %c%d%s”,’c’’10’,”there”); Same no of format &arg in order Insufficient arg =output undefined More=remind discarded Printf() return=return the no of character printed If it –ve= error occured
Field width Integer between % and format code Indicate min length %5d,%7s..etc %05d=min length 5with 0
Precision modifier Places after field width Indicate decimal point(in floating point Integer=min no of digit String=max.length
Cont…….. %10.4=atleast 10 character wide with 4 decimal place %5.7s least 5 max7
Right & left justified If field width higher than data=data places on the right side of the field (default) Least justify=force data to print on left side,can be done by giving –ve %-10.2=left justified 10 char with 2 decimal point
Code-format Code format %c                           character %d                            decimal %f                             floating point %s                             string
Format modifier 2 type of modifier            long & short %ld=long to be displayed %hu=short inttobe displayed
%n-command It causes= generation of no. of char written Pointer to be specified in the arg –list Example int; printf(“This is a test%n”,&i); printf(“%d”,i); Output      “this is a test”
Putchar() Format        #include<stdio.h> intputchar(intch); Write  into the stdout Example      for(; *str;str++) putchar(*str)
puts Format       #include<stdio.h> int puts(const char *str);       write  string pointed NULL char=newline Return non-negative=successful writing EOF                             =failure
program #include<stdio.h> #include<string.h> Int main() {    char str[80]; strcpy(str,”this is an example”);     puts(str);     return 0;  }
Scanf() Format      #include<stdio.h> intscanf(constchar * format…….) Read stdin & store in variable pointed by arg list can read the datatype & converts into internal function
Cont…….. Scanf(“%d%d”,&a,&c)     Accept as 10 2 and not as 10,2 Scanf(“%20s”,address)       input less than 20 character
    DYNAMIC MEMORY ALLOCATION
Basic Idea situations where data is dynamic in nature. Amount of data cannot be predicted beforehand. Number of data item keeps changing during program execution. Such situations can be handled more easily and effectively using dynamic memory management techniques.
CONT……….. C language requires the number of elements in an array to be specified at compile time. Often leads to wastage or memory space or program failure. Dynamic Memory Allocation Memory space required can be specified at the time of execution. C supports allocating and freeing memory dynamically using library routines.
Memory Allocation Process  in C Local variables Stack Free memory Heap Global variables Permanent storage area Instructions
The program instructions and the global variables are stored in a region known as permanent storage area. The local variables are stored in another area called stack. The memory space between these two areas is available for dynamic allocation during execution of the program. This free region is called the heap. The size of the heap keeps changing
Memory Allocation Functions malloc: Allocates requested number of bytes and returns a pointer to the first byte of the allocated space. calloc: Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. free : Frees previously allocated space. realloc: Modifies the size of previously allocated space.
Dynamic Memory Allocation  used to dynamically create space for arrays, structures, etc. int main () {        int *a ;        int n;        ....        a = (int *) calloc (n, sizeof(int));          .... } a = malloc (n*sizeof(int));
void read_array (int *a, int n) ; int sum_array (int *a, int n) ; void wrt_array (int *a, int n) ; int  main ()  {           int *a, n;           printf (“Input n: “) ;           scanf (“%d”, &n) ;           a = calloc (n, sizeof (int)) ;           read_array (a, n) ;           wrt_array (a, n) ;           printf (“Sum = %d”, sum_array(a, n); }
void read_array (int *a, int n) {         int i;         for (i=0; i<n; i++) 	    scanf (“%d”, &a[i]) ; } void sum_array (int *a, int n) {          int i, sum=0;          for (i=0; i<n; i++)                 sum += a[i] ;          return sum; } void wrt_array (int *a, int n) {          int i;          ........ }
                                    THANKS

Contenu connexe

Tendances

9. pointer, pointer & function
9. pointer, pointer & function9. pointer, pointer & function
9. pointer, pointer & function
웅식 전
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
eShikshak
 

Tendances (20)

C Programming Language Part 9
C Programming Language Part 9C Programming Language Part 9
C Programming Language Part 9
 
8 arrays and pointers
8  arrays and pointers8  arrays and pointers
8 arrays and pointers
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
 
9. pointer, pointer & function
9. pointer, pointer & function9. pointer, pointer & function
9. pointer, pointer & function
 
Input And Output
 Input And Output Input And Output
Input And Output
 
Basic Input and Output
Basic Input and OutputBasic Input and Output
Basic Input and Output
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
 
CPU INPUT OUTPUT
CPU INPUT OUTPUT CPU INPUT OUTPUT
CPU INPUT OUTPUT
 
Presention programming
Presention programmingPresention programming
Presention programming
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointer
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and Output
 
Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 

En vedette

Oferta estatal de formación continua 2012
Oferta  estatal de formación continua 2012Oferta  estatal de formación continua 2012
Oferta estatal de formación continua 2012
IREF ORIENTE
 
Progressive relations
Progressive relationsProgressive relations
Progressive relations
Progrel
 
Complejidad, Aprendizaje y Tecnologías de Información y Comunicación
Complejidad, Aprendizaje y Tecnologías de Información y ComunicaciónComplejidad, Aprendizaje y Tecnologías de Información y Comunicación
Complejidad, Aprendizaje y Tecnologías de Información y Comunicación
IREF ORIENTE
 
I vantaggi della gestione documentale
I vantaggi della gestione documentaleI vantaggi della gestione documentale
I vantaggi della gestione documentale
AlmudenaLumeras
 
Presentation Calibrate Paulh2012
Presentation Calibrate Paulh2012Presentation Calibrate Paulh2012
Presentation Calibrate Paulh2012
PHOLLINGTON
 
Calibrate Presentation 102012
Calibrate Presentation 102012Calibrate Presentation 102012
Calibrate Presentation 102012
PHOLLINGTON
 
Ofertas de carrera magisterial puebla
Ofertas de carrera magisterial pueblaOfertas de carrera magisterial puebla
Ofertas de carrera magisterial puebla
IREF ORIENTE
 
úLtimo formato con formula
úLtimo formato con formulaúLtimo formato con formula
úLtimo formato con formula
IREF ORIENTE
 
inventory control & ABC analysis ppt
inventory control & ABC analysis pptinventory control & ABC analysis ppt
inventory control & ABC analysis ppt
hyderali123
 

En vedette (18)

Oferta estatal de formación continua 2012
Oferta  estatal de formación continua 2012Oferta  estatal de formación continua 2012
Oferta estatal de formación continua 2012
 
Calibrate Presentation 102012
Calibrate Presentation 102012Calibrate Presentation 102012
Calibrate Presentation 102012
 
Como
ComoComo
Como
 
Grand Vacation Club Membership
Grand Vacation Club MembershipGrand Vacation Club Membership
Grand Vacation Club Membership
 
Progressive relations
Progressive relationsProgressive relations
Progressive relations
 
Index hotel club
Index hotel clubIndex hotel club
Index hotel club
 
Complejidad, Aprendizaje y Tecnologías de Información y Comunicación
Complejidad, Aprendizaje y Tecnologías de Información y ComunicaciónComplejidad, Aprendizaje y Tecnologías de Información y Comunicación
Complejidad, Aprendizaje y Tecnologías de Información y Comunicación
 
I vantaggi della gestione documentale
I vantaggi della gestione documentaleI vantaggi della gestione documentale
I vantaggi della gestione documentale
 
Como
ComoComo
Como
 
Presentation Calibrate Paulh2012
Presentation Calibrate Paulh2012Presentation Calibrate Paulh2012
Presentation Calibrate Paulh2012
 
Calibrate Presentation 102012
Calibrate Presentation 102012Calibrate Presentation 102012
Calibrate Presentation 102012
 
Mengenal Undur Undur
Mengenal Undur UndurMengenal Undur Undur
Mengenal Undur Undur
 
Hidram - Pompa Air tanpa Listrik & Minyak
Hidram - Pompa Air tanpa Listrik & MinyakHidram - Pompa Air tanpa Listrik & Minyak
Hidram - Pompa Air tanpa Listrik & Minyak
 
Teknologi Pompa Hidraulik Ram
Teknologi Pompa Hidraulik RamTeknologi Pompa Hidraulik Ram
Teknologi Pompa Hidraulik Ram
 
Ofertas de carrera magisterial puebla
Ofertas de carrera magisterial pueblaOfertas de carrera magisterial puebla
Ofertas de carrera magisterial puebla
 
úLtimo formato con formula
úLtimo formato con formulaúLtimo formato con formula
úLtimo formato con formula
 
Internal appraisal of the firm
Internal appraisal of the firmInternal appraisal of the firm
Internal appraisal of the firm
 
inventory control & ABC analysis ppt
inventory control & ABC analysis pptinventory control & ABC analysis ppt
inventory control & ABC analysis ppt
 

Similaire à Input output functions

Similaire à Input output functions (20)

Unit 5 Foc
Unit 5 FocUnit 5 Foc
Unit 5 Foc
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
Unit2 C
Unit2 C Unit2 C
Unit2 C
 
Unit2 C
Unit2 CUnit2 C
Unit2 C
 
string , pointer
string , pointerstring , pointer
string , pointer
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
 
C programming
C programmingC programming
C programming
 
7 functions
7  functions7  functions
7 functions
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using C
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Tut1
Tut1Tut1
Tut1
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
Fucntions & Pointers in C
Fucntions & Pointers in CFucntions & Pointers in C
Fucntions & Pointers in C
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Functions
FunctionsFunctions
Functions
 
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
 
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstack
 

Dernier

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 

Dernier (20)

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 

Input output functions

  • 2. INTRODUCTION Reading, writing & processing are the 3 essential function Inputting data 2 types assignment (a==5) Through functions(scanf(),getchar() etc) Output only functions (printf(),putchar()..etc Header file for input & output functions #include<stdio.h>
  • 3. Reading a chara using getchar getchar() read one chara at a time Syntax variable name=getchar(); Wait until the key is pressed,then value inputted will assigned to the variable Example name= getchar();
  • 4. program #include<stdio.h> main() { char answer; Printf(“would you like to know my name?”); Printf(“Type Y for yes & N for no”); answer=getchar(); If(answer==Y !! answer== y) Printf(“my name is busy bee”); else printf(“you are good for nothing”); }
  • 5. Successively read character ------- ------ char character; character=‘ ‘ while(character!= ‘’) { character=getchar(); } ------ ------
  • 6. gets Format #include<stdio.h> char*gets(char*str); Read character from the input and places in array pointed by the string Read until EOF(End off File) or “” is generated Reading successfully *str return Failure return NULL No limit of no of characters
  • 7. program #include< stdio.h> #include<stdlib.h> Int main void() { FILE *fp; Char fname[128]; Printf(“enter the filename”); gets(filename); If((fp=fopen(fname,”r”))==NULL){ Printf(“cannot open the file”); exit(1); } fclose(fp); Return0; }
  • 8. printf Format #include<stdio.h> intprintf(const char*format,…..); Write stdoutarg Format consist 2 item character the way the arg defined
  • 9. Cont………. Printf(“Hi %c%d%s”,’c’’10’,”there”); Same no of format &arg in order Insufficient arg =output undefined More=remind discarded Printf() return=return the no of character printed If it –ve= error occured
  • 10. Field width Integer between % and format code Indicate min length %5d,%7s..etc %05d=min length 5with 0
  • 11. Precision modifier Places after field width Indicate decimal point(in floating point Integer=min no of digit String=max.length
  • 12. Cont…….. %10.4=atleast 10 character wide with 4 decimal place %5.7s least 5 max7
  • 13. Right & left justified If field width higher than data=data places on the right side of the field (default) Least justify=force data to print on left side,can be done by giving –ve %-10.2=left justified 10 char with 2 decimal point
  • 14. Code-format Code format %c character %d decimal %f floating point %s string
  • 15. Format modifier 2 type of modifier long & short %ld=long to be displayed %hu=short inttobe displayed
  • 16. %n-command It causes= generation of no. of char written Pointer to be specified in the arg –list Example int; printf(“This is a test%n”,&i); printf(“%d”,i); Output “this is a test”
  • 17. Putchar() Format #include<stdio.h> intputchar(intch); Write into the stdout Example for(; *str;str++) putchar(*str)
  • 18. puts Format #include<stdio.h> int puts(const char *str); write string pointed NULL char=newline Return non-negative=successful writing EOF =failure
  • 19. program #include<stdio.h> #include<string.h> Int main() { char str[80]; strcpy(str,”this is an example”); puts(str); return 0; }
  • 20. Scanf() Format #include<stdio.h> intscanf(constchar * format…….) Read stdin & store in variable pointed by arg list can read the datatype & converts into internal function
  • 21. Cont…….. Scanf(“%d%d”,&a,&c) Accept as 10 2 and not as 10,2 Scanf(“%20s”,address) input less than 20 character
  • 22. DYNAMIC MEMORY ALLOCATION
  • 23. Basic Idea situations where data is dynamic in nature. Amount of data cannot be predicted beforehand. Number of data item keeps changing during program execution. Such situations can be handled more easily and effectively using dynamic memory management techniques.
  • 24. CONT……….. C language requires the number of elements in an array to be specified at compile time. Often leads to wastage or memory space or program failure. Dynamic Memory Allocation Memory space required can be specified at the time of execution. C supports allocating and freeing memory dynamically using library routines.
  • 25. Memory Allocation Process in C Local variables Stack Free memory Heap Global variables Permanent storage area Instructions
  • 26. The program instructions and the global variables are stored in a region known as permanent storage area. The local variables are stored in another area called stack. The memory space between these two areas is available for dynamic allocation during execution of the program. This free region is called the heap. The size of the heap keeps changing
  • 27. Memory Allocation Functions malloc: Allocates requested number of bytes and returns a pointer to the first byte of the allocated space. calloc: Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. free : Frees previously allocated space. realloc: Modifies the size of previously allocated space.
  • 28. Dynamic Memory Allocation used to dynamically create space for arrays, structures, etc. int main () { int *a ; int n; .... a = (int *) calloc (n, sizeof(int)); .... } a = malloc (n*sizeof(int));
  • 29. void read_array (int *a, int n) ; int sum_array (int *a, int n) ; void wrt_array (int *a, int n) ; int main () { int *a, n; printf (“Input n: “) ; scanf (“%d”, &n) ; a = calloc (n, sizeof (int)) ; read_array (a, n) ; wrt_array (a, n) ; printf (“Sum = %d”, sum_array(a, n); }
  • 30. void read_array (int *a, int n) { int i; for (i=0; i<n; i++) scanf (“%d”, &a[i]) ; } void sum_array (int *a, int n) { int i, sum=0; for (i=0; i<n; i++) sum += a[i] ; return sum; } void wrt_array (int *a, int n) { int i; ........ }
  • 31. THANKS