SlideShare a Scribd company logo
1 of 16
References
      and
Dynamic Memory
   Allocation
OBJECTIVES
• To be able to use references as function
  parameters.
• To be able to return references by
  functions
• To understand the difference between
  static and dynamic memory allocation
• To be able to allocate, process and
  deallocate dynamic arrays
PASSING REFERENCES TO
         FUNCTIONS

• 3 methods for passing values to
  functions: by value, address,
  reference.

• When passed to functions, references
  have a clear advantage over pointers.
void set(int x, int &ce, int &co)
{
  if((x%2)==0)
        ce++;
  else
       co++;                Passing by reference
}
                            - Is like passing the address of variable used as
int main(){                    argument in function call.
    int num,
                         -   When reference is used within the function,
    int even = 0;            compiler automatically uses odd variable, which
    int odd = 0;             is referenced by co.


    cin>>num;
    set(num, even, odd);
    cout<<“even:”<<even<<“ odd:”<<odd;
}
Reference parameter can be preceded with const to prevent a
 function from changing them inadvertently
 void fun(const int &cref)
 {
    cout<<cref/15;      //Okay
    cref++;             //ERROR! Can’t modify a const reference
 }


//Pointers as function parameters

void set(int x, int *ce, int *co){
  if((x%2)==0)
        *ce++;           //A pointer has to be dereferenced
  else
       *co++;
}
set(num, &even, &odd);                //Function called
Both same effect, but references as function
     parameter have several advantages

• Code is cleaner, no *.

• Does not have to remember to pass address of
  function argument.

• Unlike passing with a pointer, no memory location
  required.
RETURNING REFERENCES BY
        FUNCTIONS

• A function may return a reference.

• Returning a reference by a function
  also permits the function to be called
  from left side of assignment operator.
Function returns a reference to the a[n] array
const int SIZE = 6;
                             element.
int & put_val(int a[], int n){
    if(n>=SIZE || n<0){
          cout<<“Out of boundaries”; exit(1);
    }
    return a[n]; }                                        OUTPUT:
                                                          array[0] = 0
                                                          array[1] = 2
   // put_val(array, i) = i *2;
                                                          array[2] = 4
   // array[I] = i *2;
                                                          array[3] = 6
                                                          array[4] = 8
int main(){                                               array[5] = 10
   int array[SIZE];
   for(int i=0; i<SIZE; i++)
           put_val(array, i)=i*2;    //function call on the left
  for(int j=0; j<SIZE; j++)
           cout<<“array[“<<j<<“] = “<<array[j]<<endl;
}
• Less prone error than a direct assignment.

• put_val() checks at runtime that the array
  boundaries are not exceeded before it returns
  a reference to an array element.

• Prevents runtime errors such as array
  overflows/underflows(caused by assigning a
  value to an array element specified by the
  index that is outside of the boundaries of the
  array)
DYNAMIC
 MEMORY
ALLOCATION
STATIC VERSUS DYNAMIC
• STATIC MEMORY ALLOCATION - fixed size array to allocate
  memory.
• An amount of memory allocated - reserved when the program is loaded
  into memory.
• Could fail if run on comp. system lack enough memory.

struct comp_part{
   char code[7];
   char description[30];
   int on_stock;
   int sold;
   float price;
};

comp_part list[100];
• DYNAMIC MEMORY ALLOCATION solve
  this problem.
• Allocate memory at run-time.
• pointer_var = new data_type(initial value);
• delete pointer_var;
• Eg:
  float *fpt = new float(0.0);
 if(fpt==0){                    //checks for memory allocation error
    cout<<“Memory allocation error.”; exit(1);
 }
*fpt = 3.45;                    //uses pointer to access memory
cout<<*fpt;
delete fpt;                    //frees memory allocate dynamically
Memory Leak

float *ptr = new float;   //Allocates 1st block
*ptr = 7.9;                //Accesses 1st block
ptr = new float;           //Allocates 2nd block
*ptr = 5.1;               //Accesses 2nd block


• 1st memory block not deleted, address lost.
• Pointer contain address of 2nd block.
• Without delete, causes memory leak.
DYNAMIC ARRAY
• Dynamically allocated array - variable size.
• Allocate single-dimensional dynamic array:-
      Pointer_var = new data_type[size];
• Deallocate single-dimensional dynamic array:-
      Delete []pointer_var
• Eg.:-

int *ptr;
ptr = new int[10];

for(int i=0; i<10; i++)
     ptr[i] = (i+1)*2;
delete []ptr;
•Allocate two-dimensional dynamic array:-
      data_type **pointer_var;
      pointer_var = new data_type *[size];
•Deallocate two-dimensional dynamic array:-
      as shown in paper.

More Related Content

What's hot (20)

Pointer
PointerPointer
Pointer
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
 
This pointer
This pointerThis pointer
This pointer
 
Arrays
ArraysArrays
Arrays
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Function
FunctionFunction
Function
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Collection frame work
Collection  frame workCollection  frame work
Collection frame work
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointers_c
Pointers_cPointers_c
Pointers_c
 
Arrays
ArraysArrays
Arrays
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
 
Multidimensional arrays in C++
Multidimensional arrays in C++Multidimensional arrays in C++
Multidimensional arrays in C++
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
Pointers
PointersPointers
Pointers
 
C tech questions
C tech questionsC tech questions
C tech questions
 

Similar to Chp4(ref dynamic) (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec2
Lec2Lec2
Lec2
 
Link list
Link listLink list
Link list
 
pointer_in_c_programming_structure and uses.pptx
pointer_in_c_programming_structure and uses.pptxpointer_in_c_programming_structure and uses.pptx
pointer_in_c_programming_structure and uses.pptx
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec2
Lec2Lec2
Lec2
 
Lec2&3_DataStructure
Lec2&3_DataStructureLec2&3_DataStructure
Lec2&3_DataStructure
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
pointers
pointerspointers
pointers
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 

Recently uploaded

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Chp4(ref dynamic)

  • 1. References and Dynamic Memory Allocation
  • 2. OBJECTIVES • To be able to use references as function parameters. • To be able to return references by functions • To understand the difference between static and dynamic memory allocation • To be able to allocate, process and deallocate dynamic arrays
  • 3. PASSING REFERENCES TO FUNCTIONS • 3 methods for passing values to functions: by value, address, reference. • When passed to functions, references have a clear advantage over pointers.
  • 4. void set(int x, int &ce, int &co) { if((x%2)==0) ce++; else co++; Passing by reference } - Is like passing the address of variable used as int main(){ argument in function call. int num, - When reference is used within the function, int even = 0; compiler automatically uses odd variable, which int odd = 0; is referenced by co. cin>>num; set(num, even, odd); cout<<“even:”<<even<<“ odd:”<<odd; }
  • 5. Reference parameter can be preceded with const to prevent a function from changing them inadvertently void fun(const int &cref) { cout<<cref/15; //Okay cref++; //ERROR! Can’t modify a const reference } //Pointers as function parameters void set(int x, int *ce, int *co){ if((x%2)==0) *ce++; //A pointer has to be dereferenced else *co++; } set(num, &even, &odd); //Function called
  • 6. Both same effect, but references as function parameter have several advantages • Code is cleaner, no *. • Does not have to remember to pass address of function argument. • Unlike passing with a pointer, no memory location required.
  • 7. RETURNING REFERENCES BY FUNCTIONS • A function may return a reference. • Returning a reference by a function also permits the function to be called from left side of assignment operator.
  • 8. Function returns a reference to the a[n] array const int SIZE = 6; element. int & put_val(int a[], int n){ if(n>=SIZE || n<0){ cout<<“Out of boundaries”; exit(1); } return a[n]; } OUTPUT: array[0] = 0 array[1] = 2 // put_val(array, i) = i *2; array[2] = 4 // array[I] = i *2; array[3] = 6 array[4] = 8 int main(){ array[5] = 10 int array[SIZE]; for(int i=0; i<SIZE; i++) put_val(array, i)=i*2; //function call on the left for(int j=0; j<SIZE; j++) cout<<“array[“<<j<<“] = “<<array[j]<<endl; }
  • 9. • Less prone error than a direct assignment. • put_val() checks at runtime that the array boundaries are not exceeded before it returns a reference to an array element. • Prevents runtime errors such as array overflows/underflows(caused by assigning a value to an array element specified by the index that is outside of the boundaries of the array)
  • 11. STATIC VERSUS DYNAMIC • STATIC MEMORY ALLOCATION - fixed size array to allocate memory. • An amount of memory allocated - reserved when the program is loaded into memory. • Could fail if run on comp. system lack enough memory. struct comp_part{ char code[7]; char description[30]; int on_stock; int sold; float price; }; comp_part list[100];
  • 12. • DYNAMIC MEMORY ALLOCATION solve this problem. • Allocate memory at run-time. • pointer_var = new data_type(initial value); • delete pointer_var; • Eg: float *fpt = new float(0.0); if(fpt==0){ //checks for memory allocation error cout<<“Memory allocation error.”; exit(1); } *fpt = 3.45; //uses pointer to access memory cout<<*fpt; delete fpt; //frees memory allocate dynamically
  • 13. Memory Leak float *ptr = new float; //Allocates 1st block *ptr = 7.9; //Accesses 1st block ptr = new float; //Allocates 2nd block *ptr = 5.1; //Accesses 2nd block • 1st memory block not deleted, address lost. • Pointer contain address of 2nd block. • Without delete, causes memory leak.
  • 15. • Dynamically allocated array - variable size. • Allocate single-dimensional dynamic array:- Pointer_var = new data_type[size]; • Deallocate single-dimensional dynamic array:- Delete []pointer_var • Eg.:- int *ptr; ptr = new int[10]; for(int i=0; i<10; i++) ptr[i] = (i+1)*2; delete []ptr;
  • 16. •Allocate two-dimensional dynamic array:- data_type **pointer_var; pointer_var = new data_type *[size]; •Deallocate two-dimensional dynamic array:- as shown in paper.