C++ Return Array: Complete Guide with Examples
In C++, arrays cannot be directly returned as a function’s return value because the array name degrades to a pointer to the first element of the array. However, you can return an array using pointers or references.
Here is an example of returning an array using pointers:
#include <iostream>
int* createArray(int size) {
int* arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
return arr;
}
int main() {
int size = 5;
int* arr = createArray(size);
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
// Remember to delete the dynamically allocated array to avoid memory leaks
delete[] arr;
return 0;
}
Additionally, you can also use references to return arrays, as shown in the following code example:
#include <iostream>
void createArray(int*& arr, int size) {
arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
}
int main() {
int size = 5;
int* arr;
createArray(arr, size);
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
// Remember to delete the dynamically allocated array to avoid memory leaks
delete[] arr;
return 0;
}
In both cases, an array is dynamically allocated and the address of the array is returned. It is important to note that the dynamically allocated memory must be manually released after use to avoid memory leaks.