SlideShare a Scribd company logo
1 of 29
Download to read offline
Lecture 6
C
Language
ENG : HATEM ABD EL-SALAM
• Casting
• Dynamic Memory Allocation
• Scope and Lifetime
Agenda
Casting (Cont.)
• Type casting is a way to convert a variable from one data type to another data
type. For example, if you want to store a long value into a simple integer then
you can type cast long to int. You can convert values from one type to another
explicitly using the cast operator.
There are two types of type casting in c language.
1. Implicit Conversion
2. Explicit Conversion
Casting (Cont.)
1-Implicit conversion
• Implicit conversions do not required any operator for converted . They are
automatically performed when a value is copied to a compatible type in
program.
Casting (Cont.)
1- Explicit conversion
• In c language , Many conversions, specially those that imply a different
interpretation of the value, require an explicit conversion.
Casting (Cont.)
Inbuilt Typecast Functions In C
• There are many inbuilt typecasting functions available in C language which
performs data type conversion from one type to another.
Dynamic Memory Allocation
• In C, the exact size of array is unknown until compile time, i.e., the time
when a compiler compiles your code into a computer understandable
language. So, sometimes the size of the array can be insufficient or more than
required.
• Dynamic memory allocation allows your program to obtain more memory
space while running, or to release it if it's not required.
• In simple terms, Dynamic memory allocation allows you to manually handle
memory space for your program.
Dynamic Memory Allocation (Cont.)
• there are 4 library functions under "stdlib.h" for dynamic memory allocation.
Dynamic Memory Allocation (Cont.)
malloc()
• The name malloc stands for "memory allocation".
• The function malloc() reserves a block of memory of specified size and
return a pointer of type void which can be casted into pointer of any
form.
• Syntax of malloc()
Dynamic Memory Allocation (Cont.)
• Here, ptr is pointer of cast-type. The malloc() function returns a
pointer to an area of memory with size of byte size. If the space is
insufficient, allocation fails and returns NULL pointer.
• This statement will allocate either 200 or 400 according to size of int 2
or 4 bytes respectively and the pointer points to the address of first
byte of memory.
EXAMPLE PROGRAM FOR MALLOC() FUNCTION IN C
Dynamic Memory Allocation (Cont.)
calloc()
• The name calloc stands for "contiguous allocation".
• The only difference between malloc() and calloc() is that, malloc()
allocates single block of memory whereas calloc() allocates multiple
blocks of memory each of same size and sets all bytes to zero.
• Syntax of calloc()
Dynamic Memory Allocation (Cont.)
• example:
• This statement allocates contiguous space in memory for an array of 25
elements each of size of float, i.e, 4 bytes.
EXAMPLE PROGRAM FOR CALLOC() FUNCTION IN C
Dynamic Memory Allocation (Cont.)
free()
• Dynamically allocated memory created with either calloc() or malloc()
doesn't get freed on its own. You must explicitly use free() to release the
space.
• Syntax of free()
• This statement frees the space allocated in the memory pointed by ptr.
Dynamic Memory Allocation (Cont.)
realloc()
• If the previously allocated memory is insufficient or more than
required, you can change the previously allocated memory size using
realloc().
• Syntax of realloc()
• Here, ptr is reallocated with size of newsize.
EXAMPLE PROGRAM FOR REALLOC() AND FREE() FUNCTIONS IN C
Dynamic Memory Allocation (Cont.)
• Difference between static memory allocation and dynamic memory
allocation in c.
Dynamic Memory Allocation (Cont.)
• Difference between malloc() and calloc() functions in c.
Scope and Lifetime
• Every variable in C programming has two properties: type and storage class.
• Type refers to the data type of a variable. And, storage class determines the scope and
lifetime of a variable.
There are 5 types of storage class:
1. automatic
2. external
3. static
4. Register
5. Constants
Scope and Lifetime(Cont.)
1-Local Variable
• The variables declared inside the function are automatic or local variables.
• The local variables exist only inside the function in which it is declared. When the
function exits, the local variables are destroyed.
• In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed when
main() exits.
Scope and Lifetime(Cont.)
Global Variable
• Variables that are declared outside of all functions are known as external
variables. External or global variables are accessible to any function.
Scope and Lifetime(Cont.)
2-External Variable
• Suppose, a global variable is declared in file1. If you try to use that variable in a
different file file2, the compiler will complain. To solve this problem, keyword
extern is used in file2 to indicate that the external variable is declared in another
file.
Scope and Lifetime(Cont.)
3-Register Variable
• The register keyword is used to declare register variables. register variables were
supposed to be faster than local variables.
• However, modern compilers are very good at code optimization and there is a
rare chance that using register variables will make your program faster.
Scope and Lifetime(Cont.)
4-Static Variable
• A static variable is declared by using keyword static.
• The value of a static variable persists until the end of the program.
Scope and Lifetime(Cont.)
Explanation of program
• During the first function call, the value of c is equal to 0. Then, it's value is
increased by 5.
• During the second function call, variable c is not initialized to 0 again. It's
because c is a static variable. So, 5 is displayed on the screen.
Scope and Lifetime(Cont.)
4-Constants Variable
• A constant is a value or an identifier whose value cannot be altered in a program.
For example: 1, 2.5, "C programming is easy", etc.
• Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this
program.
Lecture 6 C Language: Casting, Dynamic Memory Allocation, Scope and Lifetime

More Related Content

What's hot

Compiler in System Programming/Code Optimization techniques in System Program...
Compiler in System Programming/Code Optimization techniques in System Program...Compiler in System Programming/Code Optimization techniques in System Program...
Compiler in System Programming/Code Optimization techniques in System Program...Janki Shah
 
Instruction Set (Part 2)
Instruction Set (Part 2)Instruction Set (Part 2)
Instruction Set (Part 2)Ajeng Savitri
 
Unit v memory & programmable logic devices
Unit v   memory & programmable logic devicesUnit v   memory & programmable logic devices
Unit v memory & programmable logic devicesKanmaniRajamanickam
 
Introduction to Assembly Language
Introduction to Assembly Language Introduction to Assembly Language
Introduction to Assembly Language ApekshaShinde6
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler designKuppusamy P
 
Assembly Language Basics
Assembly Language BasicsAssembly Language Basics
Assembly Language BasicsEducation Front
 
Lecture 4 assembly language
Lecture 4   assembly languageLecture 4   assembly language
Lecture 4 assembly languagePradeep Kumar TS
 
Programming the basic computer
Programming the basic computerProgramming the basic computer
Programming the basic computerKamal Acharya
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler DesignKuppusamy P
 
Learning New Semi-Supervised Deep Auto-encoder Features for Statistical Machi...
Learning New Semi-Supervised Deep Auto-encoder Features for Statistical Machi...Learning New Semi-Supervised Deep Auto-encoder Features for Statistical Machi...
Learning New Semi-Supervised Deep Auto-encoder Features for Statistical Machi...Vimukthi Wickramasinghe
 
Presentation on C++ programming
Presentation on C++ programming Presentation on C++ programming
Presentation on C++ programming AditiTibile
 
Supporting Arrays and Allocatables in LFortran
Supporting Arrays and Allocatables in LFortranSupporting Arrays and Allocatables in LFortran
Supporting Arrays and Allocatables in LFortranGagandeep Singh
 

What's hot (20)

Compiler in System Programming/Code Optimization techniques in System Program...
Compiler in System Programming/Code Optimization techniques in System Program...Compiler in System Programming/Code Optimization techniques in System Program...
Compiler in System Programming/Code Optimization techniques in System Program...
 
C basics
C basicsC basics
C basics
 
TensorRT survey
TensorRT surveyTensorRT survey
TensorRT survey
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Run time storage
Run time storageRun time storage
Run time storage
 
Instruction Set (Part 2)
Instruction Set (Part 2)Instruction Set (Part 2)
Instruction Set (Part 2)
 
Unit v memory & programmable logic devices
Unit v   memory & programmable logic devicesUnit v   memory & programmable logic devices
Unit v memory & programmable logic devices
 
Introduction to Assembly Language
Introduction to Assembly Language Introduction to Assembly Language
Introduction to Assembly Language
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler design
 
Assembly Language Basics
Assembly Language BasicsAssembly Language Basics
Assembly Language Basics
 
Optimization
OptimizationOptimization
Optimization
 
Lecture 4 assembly language
Lecture 4   assembly languageLecture 4   assembly language
Lecture 4 assembly language
 
Programming the basic computer
Programming the basic computerProgramming the basic computer
Programming the basic computer
 
Compiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent OptimizationsCompiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent Optimizations
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler Design
 
Learning New Semi-Supervised Deep Auto-encoder Features for Statistical Machi...
Learning New Semi-Supervised Deep Auto-encoder Features for Statistical Machi...Learning New Semi-Supervised Deep Auto-encoder Features for Statistical Machi...
Learning New Semi-Supervised Deep Auto-encoder Features for Statistical Machi...
 
Presentation on C++ programming
Presentation on C++ programming Presentation on C++ programming
Presentation on C++ programming
 
Embedded C - Lecture 3
Embedded C - Lecture 3Embedded C - Lecture 3
Embedded C - Lecture 3
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
 
Supporting Arrays and Allocatables in LFortran
Supporting Arrays and Allocatables in LFortranSupporting Arrays and Allocatables in LFortran
Supporting Arrays and Allocatables in LFortran
 

Similar to Lecture 6 C Language: Casting, Dynamic Memory Allocation, Scope and Lifetime

Similar to Lecture 6 C Language: Casting, Dynamic Memory Allocation, Scope and Lifetime (20)

Embedded _c_
Embedded  _c_Embedded  _c_
Embedded _c_
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
 
Storage classes, linkage & memory management
Storage classes, linkage & memory managementStorage classes, linkage & memory management
Storage classes, linkage & memory management
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
 
C interview questions
C interview questionsC interview questions
C interview questions
 
STORAGE CLASS.pptx
STORAGE CLASS.pptxSTORAGE CLASS.pptx
STORAGE CLASS.pptx
 
C language
C languageC language
C language
 
Computer Programming In C.pptx
Computer Programming In C.pptxComputer Programming In C.pptx
Computer Programming In C.pptx
 
C som-programmeringssprog-bt
C som-programmeringssprog-btC som-programmeringssprog-bt
C som-programmeringssprog-bt
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
 
C programming session9 -
C programming  session9 -C programming  session9 -
C programming session9 -
 
embedded C.pptx
embedded C.pptxembedded C.pptx
embedded C.pptx
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
Top 40 C Programming Interview Questions
Top 40 C Programming Interview QuestionsTop 40 C Programming Interview Questions
Top 40 C Programming Interview Questions
 
cs8251 unit 1 ppt
cs8251 unit 1 pptcs8251 unit 1 ppt
cs8251 unit 1 ppt
 
Memory Management.pptx
Memory Management.pptxMemory Management.pptx
Memory Management.pptx
 
C programming session7
C programming  session7C programming  session7
C programming session7
 
C programming session7
C programming  session7C programming  session7
C programming session7
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 

More from Hatem Abd El-Salam

More from Hatem Abd El-Salam (12)

Java- language Lecture 7
Java- language Lecture 7Java- language Lecture 7
Java- language Lecture 7
 
Java- language Lecture 6
Java- language Lecture 6Java- language Lecture 6
Java- language Lecture 6
 
Java- language Lecture 5
Java- language Lecture 5Java- language Lecture 5
Java- language Lecture 5
 
Java- language Lecture 4
Java- language Lecture 4Java- language Lecture 4
Java- language Lecture 4
 
Java- language Lecture 3
Java- language Lecture 3Java- language Lecture 3
Java- language Lecture 3
 
Java- Language Lecture 2
Java- Language Lecture 2Java- Language Lecture 2
Java- Language Lecture 2
 
Java- language Lecture 1
Java- language Lecture 1Java- language Lecture 1
Java- language Lecture 1
 
introduction to embedded systems part 2
introduction to embedded systems part 2introduction to embedded systems part 2
introduction to embedded systems part 2
 
introduction to embedded systems part 1
introduction to embedded systems part 1introduction to embedded systems part 1
introduction to embedded systems part 1
 
C- language Lecture 3
C- language Lecture 3C- language Lecture 3
C- language Lecture 3
 
C- Language Lecture 2
C- Language Lecture 2C- Language Lecture 2
C- Language Lecture 2
 
C-language Lecture 1
C-language Lecture 1C-language Lecture 1
C-language Lecture 1
 

Recently uploaded

_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 

Lecture 6 C Language: Casting, Dynamic Memory Allocation, Scope and Lifetime

  • 1. Lecture 6 C Language ENG : HATEM ABD EL-SALAM
  • 2. • Casting • Dynamic Memory Allocation • Scope and Lifetime Agenda
  • 3. Casting (Cont.) • Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator. There are two types of type casting in c language. 1. Implicit Conversion 2. Explicit Conversion
  • 4. Casting (Cont.) 1-Implicit conversion • Implicit conversions do not required any operator for converted . They are automatically performed when a value is copied to a compatible type in program.
  • 5. Casting (Cont.) 1- Explicit conversion • In c language , Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion.
  • 6. Casting (Cont.) Inbuilt Typecast Functions In C • There are many inbuilt typecasting functions available in C language which performs data type conversion from one type to another.
  • 7. Dynamic Memory Allocation • In C, the exact size of array is unknown until compile time, i.e., the time when a compiler compiles your code into a computer understandable language. So, sometimes the size of the array can be insufficient or more than required. • Dynamic memory allocation allows your program to obtain more memory space while running, or to release it if it's not required. • In simple terms, Dynamic memory allocation allows you to manually handle memory space for your program.
  • 8. Dynamic Memory Allocation (Cont.) • there are 4 library functions under "stdlib.h" for dynamic memory allocation.
  • 9. Dynamic Memory Allocation (Cont.) malloc() • The name malloc stands for "memory allocation". • The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. • Syntax of malloc()
  • 10. Dynamic Memory Allocation (Cont.) • Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer. • This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.
  • 11. EXAMPLE PROGRAM FOR MALLOC() FUNCTION IN C
  • 12. Dynamic Memory Allocation (Cont.) calloc() • The name calloc stands for "contiguous allocation". • The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. • Syntax of calloc()
  • 13. Dynamic Memory Allocation (Cont.) • example: • This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.
  • 14. EXAMPLE PROGRAM FOR CALLOC() FUNCTION IN C
  • 15. Dynamic Memory Allocation (Cont.) free() • Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You must explicitly use free() to release the space. • Syntax of free() • This statement frees the space allocated in the memory pointed by ptr.
  • 16. Dynamic Memory Allocation (Cont.) realloc() • If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc(). • Syntax of realloc() • Here, ptr is reallocated with size of newsize.
  • 17. EXAMPLE PROGRAM FOR REALLOC() AND FREE() FUNCTIONS IN C
  • 18. Dynamic Memory Allocation (Cont.) • Difference between static memory allocation and dynamic memory allocation in c.
  • 19. Dynamic Memory Allocation (Cont.) • Difference between malloc() and calloc() functions in c.
  • 20.
  • 21. Scope and Lifetime • Every variable in C programming has two properties: type and storage class. • Type refers to the data type of a variable. And, storage class determines the scope and lifetime of a variable. There are 5 types of storage class: 1. automatic 2. external 3. static 4. Register 5. Constants
  • 22. Scope and Lifetime(Cont.) 1-Local Variable • The variables declared inside the function are automatic or local variables. • The local variables exist only inside the function in which it is declared. When the function exits, the local variables are destroyed. • In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed when main() exits.
  • 23. Scope and Lifetime(Cont.) Global Variable • Variables that are declared outside of all functions are known as external variables. External or global variables are accessible to any function.
  • 24. Scope and Lifetime(Cont.) 2-External Variable • Suppose, a global variable is declared in file1. If you try to use that variable in a different file file2, the compiler will complain. To solve this problem, keyword extern is used in file2 to indicate that the external variable is declared in another file.
  • 25. Scope and Lifetime(Cont.) 3-Register Variable • The register keyword is used to declare register variables. register variables were supposed to be faster than local variables. • However, modern compilers are very good at code optimization and there is a rare chance that using register variables will make your program faster.
  • 26. Scope and Lifetime(Cont.) 4-Static Variable • A static variable is declared by using keyword static. • The value of a static variable persists until the end of the program.
  • 27. Scope and Lifetime(Cont.) Explanation of program • During the first function call, the value of c is equal to 0. Then, it's value is increased by 5. • During the second function call, variable c is not initialized to 0 again. It's because c is a static variable. So, 5 is displayed on the screen.
  • 28. Scope and Lifetime(Cont.) 4-Constants Variable • A constant is a value or an identifier whose value cannot be altered in a program. For example: 1, 2.5, "C programming is easy", etc. • Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.