blog
blog copied to clipboard
C++: Returning Pointers from Functions
Concept: Functions can return pointers, but you must be sure the item the pointer references still exists.
Example:
#include <iostream>
using namespace std;
int* creat_an_array(int);
int main() {
int num_values;
int* ptr = nullptr;
cout << "How many values do you want to store? ";
cin >> num_values;
ptr = creat_an_array(num_values);
for (int i = 0; i < num_values; i++) {
cout << ptr[i] << " ";
}
return 0;
}
int* creat_an_array(int size) {
int* ptr_arr = new int[size];
for (int i = 0; i < size; ++i) {
ptr_arr[i] = 1;
}
return ptr_arr;
}
Output:
How many values do you want to store? 10
1 1 1 1 1 1 1 1 1 1