SlideShare a Scribd company logo
LAB 3: REFERENCES AND POINTERS
ENG. MOHAMMED AL-OBAIDI
UNIVERSITY OF SANA’A
FACILITY OF ENGINEERING
MECHATRONICS
DEPARTMENT
QUIZ
OVERVIEW OF REFERENCES AND POINTERS
 Often need to refer to another object
 – Without making a copy of the object itself
 – Also known as “aliasing”
 Two ways to do this
 – Directly, via a reference
o • Acts as an alias for the object
o • User interacts with reference as if it were the object itself
 – Indirectly, via a pointer
o • Gives the address (in memory) of the object
o • Requires the user to do extra work: dereferencing
OVERVIEW OF REFERENCES AND POINTERS
WHAT IS A REFERENCES
 Reference is an alternative name for an existing variable (alias).
 • A variable holding an address of what it “refers to” in memory
 • But with a nicer interface
 – An alias to the object
 – Hides indirection from programmer
 • Must be typed
 – Checked by compiler
 – Again can only refer to the type to which it can point
int &r = i; // can only refer to int
 • Must always refer to something
 – Must be initialized, cannot be changed
 – More restricted than Java references
WHAT IS A POINTER
 Pointers is simply a variable that maintain as a value the address of another location in
memory.
 A variable holding an address of what it “points to” in memory
 • Can be untyped
 void * v; // can point to any type
 • However, usually they’re typed
 – Checked by compiler
 – Can only be assigned addresses of variables of the type to which it can point
int * p; // can only point to int
 • Addresses: garbage, something, nothing
 – When created: int * p = i; vs. int * q;
 q = 0; // now it points to nothing
 p = NULL; // not portable, use nullptr instead
WHAT IS A POINTER
 Pointers is simply a variable that maintain as a value the address of another location in
memory.
 A variable holding an address of what it “points to” in memory
 • Can be untyped
 void * v; // can point to any type
 • However, usually they’re typed
 – Checked by compiler
 – Can only be assigned addresses of variables of the type to which it can point
int * p; // can only point to int
 • Addresses: garbage, something, nothing
 – When created: int * p = i; vs. int * q;
 q = 0; // now it points to nothing
 p = NULL; // not portable, use nullptr instead
REFERENCE AND POINTER VARIABLES
 Variable and object values are stored in particular locations in the computer’s memory.
 Reference and pointer variables store the memory location of other variables.
 Pointers are found in C. References are a C++ variation that makes pointers easier and safer to
use.
string hello = "Hello";
string *hello_ptr = &hello;
string &hello_ref = hello;
The object hello
occupies some
computer memory.
The asterisk indicates that hello_ptr is a
pointer to a string. hello_ptr variable is
assigned the memory address of object hello
which is accessed with the “&” syntax.
The & here indicates that hello_ref is a reference to a
string. The hello_ref variable is assigned the memory
address of object hello automatically.
REFERENCE AND POINTER VARIABLES
 Difference between reference and pointers
 A reference can never be null; it must always refer to a legitimate object.
 Once established, a reference can never be changed to make it point to a different object.
 A reference does not require any explicit mechanism to dereference the memory address and
access the actual data value.
REFERENCE AND POINTER VARIABLES
DYNAMIC MEMORY ALLOCATION
 Dynamic memory allocation is the process of allocating and freeing memory during the execution
of a program.
 It is useful when the memory needs of a program are not known in advance, or when they change
during the program’s lifetime.
 It differs from static memory allocation, which is done at compile time and cannot be changed
afterwards.
DYNAMIC MEMORY ALLOCATION
 Suppose we want to create an array of integers with a size that is determined by the user’s input.
We cannot use a regular array declaration, because the size must be a constant expression. Instead,
we can use dynamic memory allocation with pointers:
int *arr; // declare a pointer to int
int n; // declare an int variable to store the size
cout << "Enter the size of the array: ";
cin >> n; // read the size from the user
arr = new int[n]; // allocate memory for n elements
of type int and assign the address to arr
// now we can use arr as a regular array, for
example:
for (int i = 0; i < n; i++) {
arr[i] = i + 1; // assign some values to the array
elements
}
for (int i = 0; i < n; i++) {
cout << arr[i] << " "; // print the array elements
}
pointer = new type; // allocate memory for one
element of type type and assign the address to
pointer
pointer = new type[size]; // allocate memory for
an array of size elements of type type and
assign the address to pointer
delete pointer; // free the memory pointed by pointer
(one element)
delete[] pointer; // free the memory pointed by pointer
(an array)
DYNAMIC MEMORY ALLOCATION
 Advantages: Some advantages of using dynamic memory allocation are:
 It allows us to create data structures with variable sizes, such as linked lists, trees, graphs, etc.
 It can improve the efficiency and performance of a program by avoiding unused or wasted
memory.
 It can avoid memory overflow errors by allocating memory only when needed.
 Disadvantages: Some disadvantages of using dynamic memory allocation are:
 It adds complexity and overhead to a program, as we need to manage the memory manually
and check for errors.
 It can cause memory leaks or errors if we forget to free the memory or use invalid pointers.
 It can fragment the memory heap, making it harder to find contiguous blocks of memory.
RELATIONSHIP BETWEEN ARRAYS AND POINTERS
 The value of an array name is the address of the first element in the array
 The value of a pointer variable is an address
 If the pointer points to the same data type as the array element then the pointer and
array name can be used interchangeably (almost).
POINTERS AND CONST IN C++
 Pointers are variables that store the address of another variable or object in memory.
 const is a keyword that indicates that a variable or object is constant, meaning its value cannot be
changed after initialization.
 Pointers and const can be used together in C++ to create different types of pointers that have
different levels of constness.
 Suppose we have two variables, a and b, of type int, and we want to create pointers to them. We
can use the following declarations:
POINTERS AND CONST IN C++
 Now we can use these pointers to access or modify the values of a and b, depending on the type of
pointer. For example:
PASSING POINTERS TO FUNCTIONS
 Pass-by-reference with pointer parameters
 We can use pointers and the dereference operator to achieve pass-by- reference
 The function parameter is a pointer
 The actual parameter can be a pointer or address of a variable
void double_data(int *int_ptr);
void double_data(int *int_ptr) {
*int_ptr *= 2;
}
POTENTIAL POINTER PITFALLS
 Uninitialized pointers
 Dangling Pointers
 Not checking if new failed to allocate memory
 Leaking memory

More Related Content

Similar to Lab 3.pptx

Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
Gamindu Udayanga
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
Md. Afif Al Mamun
 
Pointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptxPointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptx
Ananthi Palanisamy
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
TamiratDejene1
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
ShivanshuVerma11
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Vijayananda Ratnam Ch
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Monishkanungo
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
Tanmay Modi
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
tanmaymodi4
 
(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings
Nico Ludwig
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
Mca ii dfs u-2 array records and pointer
Mca ii dfs u-2 array records and pointerMca ii dfs u-2 array records and pointer
Mca ii dfs u-2 array records and pointer
Rai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 

Similar to Lab 3.pptx (20)

Pointer in c++ part1
Pointer in c++ part1Pointer in c++ part1
Pointer in c++ part1
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptxPointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptx
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings
 
C++ data types
C++ data typesC++ data types
C++ data types
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Mca ii dfs u-2 array records and pointer
Mca ii dfs u-2 array records and pointerMca ii dfs u-2 array records and pointer
Mca ii dfs u-2 array records and pointer
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
 

More from MohammedAlobaidy16

cnc_codes_and_letters.ppt
cnc_codes_and_letters.pptcnc_codes_and_letters.ppt
cnc_codes_and_letters.ppt
MohammedAlobaidy16
 
1684424.ppt
1684424.ppt1684424.ppt
1684424.ppt
MohammedAlobaidy16
 
Lab 4 (1).pdf
Lab 4 (1).pdfLab 4 (1).pdf
Lab 4 (1).pdf
MohammedAlobaidy16
 
Lab 3.pptx
Lab 3.pptxLab 3.pptx
Lab 3.pptx
MohammedAlobaidy16
 
ch22.ppt
ch22.pptch22.ppt
ch07.ppt
ch07.pptch07.ppt
LAB3_CADCAM_using_MasterCam.pptx
LAB3_CADCAM_using_MasterCam.pptxLAB3_CADCAM_using_MasterCam.pptx
LAB3_CADCAM_using_MasterCam.pptx
MohammedAlobaidy16
 
oopusingc.pptx
oopusingc.pptxoopusingc.pptx
oopusingc.pptx
MohammedAlobaidy16
 
MS Office Word.pptx
 MS Office Word.pptx MS Office Word.pptx
MS Office Word.pptx
MohammedAlobaidy16
 
MT 308 Industrial Automation.ppt
MT 308 Industrial Automation.pptMT 308 Industrial Automation.ppt
MT 308 Industrial Automation.ppt
MohammedAlobaidy16
 
ch25.ppt
ch25.pptch25.ppt
ch05.ppt
ch05.pptch05.ppt
ch02.ppt
ch02.pptch02.ppt
Lab1 - Introduction to Computer Basics Laboratory.pdf
Lab1 - Introduction to Computer Basics Laboratory.pdfLab1 - Introduction to Computer Basics Laboratory.pdf
Lab1 - Introduction to Computer Basics Laboratory.pdf
MohammedAlobaidy16
 
lab3&4.pdf
lab3&4.pdflab3&4.pdf
lab3&4.pdf
MohammedAlobaidy16
 
LAB2_Gcode_Mcode.pptx
LAB2_Gcode_Mcode.pptxLAB2_Gcode_Mcode.pptx
LAB2_Gcode_Mcode.pptx
MohammedAlobaidy16
 
4_5931536868716842982.pdf
4_5931536868716842982.pdf4_5931536868716842982.pdf
4_5931536868716842982.pdf
MohammedAlobaidy16
 
ch01.ppt
ch01.pptch01.ppt
Lab 1.pptx
Lab 1.pptxLab 1.pptx
Lab 1.pptx
MohammedAlobaidy16
 

More from MohammedAlobaidy16 (19)

cnc_codes_and_letters.ppt
cnc_codes_and_letters.pptcnc_codes_and_letters.ppt
cnc_codes_and_letters.ppt
 
1684424.ppt
1684424.ppt1684424.ppt
1684424.ppt
 
Lab 4 (1).pdf
Lab 4 (1).pdfLab 4 (1).pdf
Lab 4 (1).pdf
 
Lab 3.pptx
Lab 3.pptxLab 3.pptx
Lab 3.pptx
 
ch22.ppt
ch22.pptch22.ppt
ch22.ppt
 
ch07.ppt
ch07.pptch07.ppt
ch07.ppt
 
LAB3_CADCAM_using_MasterCam.pptx
LAB3_CADCAM_using_MasterCam.pptxLAB3_CADCAM_using_MasterCam.pptx
LAB3_CADCAM_using_MasterCam.pptx
 
oopusingc.pptx
oopusingc.pptxoopusingc.pptx
oopusingc.pptx
 
MS Office Word.pptx
 MS Office Word.pptx MS Office Word.pptx
MS Office Word.pptx
 
MT 308 Industrial Automation.ppt
MT 308 Industrial Automation.pptMT 308 Industrial Automation.ppt
MT 308 Industrial Automation.ppt
 
ch25.ppt
ch25.pptch25.ppt
ch25.ppt
 
ch05.ppt
ch05.pptch05.ppt
ch05.ppt
 
ch02.ppt
ch02.pptch02.ppt
ch02.ppt
 
Lab1 - Introduction to Computer Basics Laboratory.pdf
Lab1 - Introduction to Computer Basics Laboratory.pdfLab1 - Introduction to Computer Basics Laboratory.pdf
Lab1 - Introduction to Computer Basics Laboratory.pdf
 
lab3&4.pdf
lab3&4.pdflab3&4.pdf
lab3&4.pdf
 
LAB2_Gcode_Mcode.pptx
LAB2_Gcode_Mcode.pptxLAB2_Gcode_Mcode.pptx
LAB2_Gcode_Mcode.pptx
 
4_5931536868716842982.pdf
4_5931536868716842982.pdf4_5931536868716842982.pdf
4_5931536868716842982.pdf
 
ch01.ppt
ch01.pptch01.ppt
ch01.ppt
 
Lab 1.pptx
Lab 1.pptxLab 1.pptx
Lab 1.pptx
 

Recently uploaded

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 

Recently uploaded (20)

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 

Lab 3.pptx

  • 1. LAB 3: REFERENCES AND POINTERS ENG. MOHAMMED AL-OBAIDI UNIVERSITY OF SANA’A FACILITY OF ENGINEERING MECHATRONICS DEPARTMENT
  • 3. OVERVIEW OF REFERENCES AND POINTERS  Often need to refer to another object  – Without making a copy of the object itself  – Also known as “aliasing”  Two ways to do this  – Directly, via a reference o • Acts as an alias for the object o • User interacts with reference as if it were the object itself  – Indirectly, via a pointer o • Gives the address (in memory) of the object o • Requires the user to do extra work: dereferencing
  • 4. OVERVIEW OF REFERENCES AND POINTERS
  • 5. WHAT IS A REFERENCES  Reference is an alternative name for an existing variable (alias).  • A variable holding an address of what it “refers to” in memory  • But with a nicer interface  – An alias to the object  – Hides indirection from programmer  • Must be typed  – Checked by compiler  – Again can only refer to the type to which it can point int &r = i; // can only refer to int  • Must always refer to something  – Must be initialized, cannot be changed  – More restricted than Java references
  • 6. WHAT IS A POINTER  Pointers is simply a variable that maintain as a value the address of another location in memory.  A variable holding an address of what it “points to” in memory  • Can be untyped  void * v; // can point to any type  • However, usually they’re typed  – Checked by compiler  – Can only be assigned addresses of variables of the type to which it can point int * p; // can only point to int  • Addresses: garbage, something, nothing  – When created: int * p = i; vs. int * q;  q = 0; // now it points to nothing  p = NULL; // not portable, use nullptr instead
  • 7. WHAT IS A POINTER  Pointers is simply a variable that maintain as a value the address of another location in memory.  A variable holding an address of what it “points to” in memory  • Can be untyped  void * v; // can point to any type  • However, usually they’re typed  – Checked by compiler  – Can only be assigned addresses of variables of the type to which it can point int * p; // can only point to int  • Addresses: garbage, something, nothing  – When created: int * p = i; vs. int * q;  q = 0; // now it points to nothing  p = NULL; // not portable, use nullptr instead
  • 8. REFERENCE AND POINTER VARIABLES  Variable and object values are stored in particular locations in the computer’s memory.  Reference and pointer variables store the memory location of other variables.  Pointers are found in C. References are a C++ variation that makes pointers easier and safer to use. string hello = "Hello"; string *hello_ptr = &hello; string &hello_ref = hello; The object hello occupies some computer memory. The asterisk indicates that hello_ptr is a pointer to a string. hello_ptr variable is assigned the memory address of object hello which is accessed with the “&” syntax. The & here indicates that hello_ref is a reference to a string. The hello_ref variable is assigned the memory address of object hello automatically. REFERENCE AND POINTER VARIABLES
  • 9.  Difference between reference and pointers  A reference can never be null; it must always refer to a legitimate object.  Once established, a reference can never be changed to make it point to a different object.  A reference does not require any explicit mechanism to dereference the memory address and access the actual data value. REFERENCE AND POINTER VARIABLES
  • 10. DYNAMIC MEMORY ALLOCATION  Dynamic memory allocation is the process of allocating and freeing memory during the execution of a program.  It is useful when the memory needs of a program are not known in advance, or when they change during the program’s lifetime.  It differs from static memory allocation, which is done at compile time and cannot be changed afterwards.
  • 11. DYNAMIC MEMORY ALLOCATION  Suppose we want to create an array of integers with a size that is determined by the user’s input. We cannot use a regular array declaration, because the size must be a constant expression. Instead, we can use dynamic memory allocation with pointers: int *arr; // declare a pointer to int int n; // declare an int variable to store the size cout << "Enter the size of the array: "; cin >> n; // read the size from the user arr = new int[n]; // allocate memory for n elements of type int and assign the address to arr // now we can use arr as a regular array, for example: for (int i = 0; i < n; i++) { arr[i] = i + 1; // assign some values to the array elements } for (int i = 0; i < n; i++) { cout << arr[i] << " "; // print the array elements } pointer = new type; // allocate memory for one element of type type and assign the address to pointer pointer = new type[size]; // allocate memory for an array of size elements of type type and assign the address to pointer delete pointer; // free the memory pointed by pointer (one element) delete[] pointer; // free the memory pointed by pointer (an array)
  • 12. DYNAMIC MEMORY ALLOCATION  Advantages: Some advantages of using dynamic memory allocation are:  It allows us to create data structures with variable sizes, such as linked lists, trees, graphs, etc.  It can improve the efficiency and performance of a program by avoiding unused or wasted memory.  It can avoid memory overflow errors by allocating memory only when needed.  Disadvantages: Some disadvantages of using dynamic memory allocation are:  It adds complexity and overhead to a program, as we need to manage the memory manually and check for errors.  It can cause memory leaks or errors if we forget to free the memory or use invalid pointers.  It can fragment the memory heap, making it harder to find contiguous blocks of memory.
  • 13. RELATIONSHIP BETWEEN ARRAYS AND POINTERS  The value of an array name is the address of the first element in the array  The value of a pointer variable is an address  If the pointer points to the same data type as the array element then the pointer and array name can be used interchangeably (almost).
  • 14. POINTERS AND CONST IN C++  Pointers are variables that store the address of another variable or object in memory.  const is a keyword that indicates that a variable or object is constant, meaning its value cannot be changed after initialization.  Pointers and const can be used together in C++ to create different types of pointers that have different levels of constness.  Suppose we have two variables, a and b, of type int, and we want to create pointers to them. We can use the following declarations:
  • 15. POINTERS AND CONST IN C++  Now we can use these pointers to access or modify the values of a and b, depending on the type of pointer. For example:
  • 16. PASSING POINTERS TO FUNCTIONS  Pass-by-reference with pointer parameters  We can use pointers and the dereference operator to achieve pass-by- reference  The function parameter is a pointer  The actual parameter can be a pointer or address of a variable void double_data(int *int_ptr); void double_data(int *int_ptr) { *int_ptr *= 2; }
  • 17. POTENTIAL POINTER PITFALLS  Uninitialized pointers  Dangling Pointers  Not checking if new failed to allocate memory  Leaking memory