adding passing pointer by reference example and notes

This commit is contained in:
Jidong Xiao
2024-02-13 19:21:37 -05:00
parent 07a11d2123
commit a3754018f4
2 changed files with 30 additions and 0 deletions

View File

@@ -95,5 +95,7 @@ and lists with one or two values. Also add a test or two of a node chain with so
If you have time, write 2 versions of this function, one version should be iterative (using a for or while loop) If you have time, write 2 versions of this function, one version should be iterative (using a for or while loop)
and one version should be recursive. and one version should be recursive.
**Note**: this reverse function takes a pointer as its argument, but we are passing this pointer by reference, because we want to modify this pointer. To understand the concept of passing a pointer by reference, you are recommended to read and run this [example program](reference_to_a_pointer.cpp).
**To complete this checkpoint**, show a TA or mentor your diagram and your debugged function(s) to **To complete this checkpoint**, show a TA or mentor your diagram and your debugged function(s) to
reverse a homemade singly-linked list. reverse a homemade singly-linked list.

View File

@@ -0,0 +1,28 @@
/* This example demonstrates the usage of passing a pointer by reference.
* It is needed when you want to modify the pointer.
*/
#include <iostream>
// function to modify the value of a pointer through reference
void modifyPointer(int* & ptr, int& newValue) {
ptr = &newValue; // assign the address of newValue to the pointer
}
int main() {
int value = 42;
int* ptr = &value;
// print the original value of the pointer
std::cout << "Original value of pointer: " << *ptr << std::endl;
int newValue = 100; // new value to assign to the pointer
// pass the pointer by reference to the function, so that we can change the pointer
modifyPointer(ptr, newValue);
// print the modified value of the pointer
std::cout << "Modified value of pointer: " << *ptr << std::endl;
return 0;
}