I am reading this post [Function returning a pointer to an int array] and learning the difference between returning a pointer to int
and a pointer to an array of int
.
I got a few questions while trying to sum it up. First, take a look at this code (keeping it simple):
Functions test
and test2
return pointer to int
and a pointer to an array of int
int* test(size_t &sz) {
int *out = new int[5];
sz = 5;
return out;
}
int (*test2())[3] {
static int out[] = {1, 2, 3};
return &out;
}
How do I have to change test2
to work with dynamic array (not static)? And is it possible to pass an array size as a reference or somehow?
Main function looks as this. The code compiles.
int main() {
size_t sz;
int *array = test(sz);
for (size_t i = 0; i != sz; ++i) {
array[i] = 10;
cout << *(array + i) << " ";
}
cout << endl;
delete[] array;
int (*array2)[3] = test2();
for (size_t i = 0; i != 3; ++i) {
cout << (*array2)[i] << " ";
}
}
Result
10 10 10 10 10
1 2 3