I’d like to easily initialize an array inside the function:
int arr[]{1, 2, 3};
It simplifies calculating the size of the array:
int n = sizeof(arr) / sizeof(*arr);
However, I need this array to be preserved and be accessible outside the function.
How to do this?
For the start, I have this:
#include <iostream>
using namespace std;
int n{0};
int* g_arr{nullptr};
void f()
{
int arr[]{1, 2, 3};
n = sizeof(arr) / sizeof(*arr);
g_arr = arr; // you can't use g_arr value outside this function, since arr will be freed.
}
void b()
{
cout << n;
for (int i = 0; i < n; ++i)
{
cout << g_arr[i] << endl; // this is still wrong
}
}
int main()
{
f();
b();
}
int g_arr[3];at file scope and assign the values infarrinside the function. In fact it ceases to exist whenfreturns. If you have other requirements then you will need to detail them