arrays and pointers

closed account (G1vDizwU)
Hello all,

Please look at this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double* fct(){

	double arr[5] = {3,6,9,12,15};
	return arr;
}

//---------------------------------

int main() {

	double* d = fct();

	cout << d[0] << ' ' << d[1] << ' ' << d[2] << ' ' << d[3] << ' ' << d[4];
	cout << endl;
	
	system("pause");
	return 0;
}

How do I write (cout) the contents of d using a loop please?
Last edited on
You may want to do this :
1
2
3
4
5
double* fct(){

	static double arr[5] = {3,6,9,12,15};
	return arr;
}
If you know the exact size of the array (for example, 5), you can do something like this :
1
2
3
4
5
6
7
8
int main() {

	double* d = fct();
	for(int i = 0; i < 5; i++) cout << d[i] << ' '; cout << endl;
	
	system("pause");
	return 0;
}
Last edited on
closed account (G1vDizwU)
Thanks. Using the keyword static solved the issue. But why do we need to use that keyword for printing out the values of the array please?

Normally, when variables go out of scope, they are automatically destroyed. After fct() returns, the array is automatically destroyed, with d pointing to the array that was destroyed. Thus, doing any operations with it, results in undefined behaviour.

static allows the variable to live as long as the program, so when fct() returns, d holds the array, declared in fct().
Topic archived. No new replies allowed.