#include "std_lib_facilities.h" // comes with the book I'm reading
void f1(int* a)
{
int* p = newint[10];
for(int i = 0; i < 10; ++i) p[i] = i + 1;
a = p;
// when the function ends, shouldn't the pointer that you passed hold
// the address of the first element in the newly allocated data?
}
void f2(int* a)
// caller of function is responsible for allocating the data before calling the function
{
for(int i = 0; i < 10; ++i) a[i] = i + 1;
}
int main()
{
int* x = 0;
cout << "entering f1()" << "\n";
f1(x);
if(x == 0) cout << "x == 0" << "\n";
// why does x == 0?
int* y = newint[10];
cout << "entering f2()" << "\n";
f2(y);
if(y == 0) cout << "y == 0" << "\n";
keep_window_open();
return 0;
}
this is a pass-by-value: the name a identifies, essentially, a local variable, which holds a copy of the function call argument (that is, it's a copy of x)
a = p;
This changes this local variable 'a'. It has no effect on x.
// when the function ends, shouldn't the pointer that you passed hold
// the address of the first element in the newly allocated data?
You could achieve that by using pass-by-reference: void f1(int*& a)
or by returning the new pointer: int* f1(int* a) (although, since you're returning a heap-allocated pointer, it would be a lot better to return unique_ptr<int[]>)