diff --git a/labs/06_lists_iterators/README.md b/labs/06_lists_iterators/README.md index d7d508d..a8054e9 100644 --- a/labs/06_lists_iterators/README.md +++ b/labs/06_lists_iterators/README.md @@ -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) 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 reverse a homemade singly-linked list. diff --git a/labs/06_lists_iterators/reference_to_a_pointer.cpp b/labs/06_lists_iterators/reference_to_a_pointer.cpp new file mode 100644 index 0000000..f7682e7 --- /dev/null +++ b/labs/06_lists_iterators/reference_to_a_pointer.cpp @@ -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 + +// 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; +} +