Welcome to our deep dive into C++ Return by Pointer! This lesson is designed for both beginners and intermediates. Let's embark on this exciting journey together. š”
In C++, a function can return a value to the calling function using a pointer. This technique is known as "Return by Pointer". It is an efficient way to pass large data structures or objects between functions.
Before we delve into Return by Pointer, let's quickly recap pointers. In C++, a pointer is a variable that stores the memory address of another variable.
int number = 5;
int* pointer = &number; // '&' returns the address of the variableNow, let's create a simple function that returns a pointer.
int* getNumber() {
int* number = new int(5); // 'new' allocates memory on the heap
return number; // Returns the memory address
}Note: Always remember to delete the allocated memory when it's no longer needed to avoid memory leaks.
int* p = getNumber();
std::cout << *p; // Output: 5
delete p; // Deallocates the memoryIn this example, we'll create a dynamic array and return a pointer to it.
#include <vector>
std::vector<int>* createDynamicArray(int size) {
std::vector<int>* array = new std::vector<int>(size);
for (int i = 0; i < size; ++i)
array->at(i) = i * 2; // Filling the array with even numbers
return array;
}
int main() {
std::vector<int>* array = createDynamicArray(10);
for (int i = 0; i < 10; ++i)
std::cout << array->at(i) << " "; // Output: 0 2 4 6 8 10 12 14 16 18
delete array; // Deallocates the memory
return 0;
}Which of the following is the correct way to return a pointer to a dynamic array in C++?
That's all for today! Remember to always manage your allocated memory responsibly to avoid memory leaks. Happy coding! š”šÆ