Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

C++: Returning Pointers from Functions #210

Open Qingquan-Li opened 2 years ago

Qingquan-Li commented 2 years ago

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