Pass-by-pointer and allocate it, data gets destroyed?

I have a question about passing a pointer to a function. You have to look at the code to understand my question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "std_lib_facilities.h" // comes with the book I'm reading

void f1(int* a)
{
	int* p = new int[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 = new int[10];
	cout << "entering f2()" << "\n";
	f2(y);
	if(y == 0) cout << "y == 0" << "\n";
	keep_window_open();
	return 0;
}


Well my question is, why does x equal zero?

Thanks in advance to anyone who replies!
void f1(int* a)

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[]>)
Last edited on
@Cubbi

Thank you very much! Now I understand everything.
Topic archived. No new replies allowed.