Need help with the code

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
32
33
#include <iostream> 
using namespace std;


double *array(double a, double b)
{
	double arr[3];
	double *p;
	p=arr;
	arr[0]=a+b;
	arr[1]=a-b;
	arr[2]=a*b;

	for(int i=0; i<=2; i++)
	{
		cout<<"arr["<<i<<"]= "<<arr[i]<<"\t"<<"p["<<i<<"]= "<<*(p+i)<<endl;
	}
 return p;
}

	
int main()
{
	double *dp;
	dp=array(1.0, 2.0);

	cout<<"pointer values inside main\n";

	for(int i=0; i<=2; i++)
{
	cout<<"dp["<<i<<"]= "<<*(dp+i)<<endl;
}
}



output:
arr[0]= 3 p[0]= 3
arr[1]= -1 p[1]= -1
arr[2]= 2 p[2]= 2
pointer values inside main
dp[0]= 4.87686e-270
dp[1]= 4.21731e+15
dp[2]= 6.64617e-316

1
2
3
4
5
6
7
8
double *array(double a, double b)
{
	double arr[3];
	double *p;
	p=arr;
	//...
	return p;
}
¿Did you try to "fix" this warning?
In function ‘double* array(double, double)’:
warning: address of local variable ‘arr’ returned
I returned p, not arr.
When I am returning arr from the function I am getting this warning
I returned p, not arr.

p is a pointer. The value of pointer is an address. Teh p has the address of arr as its value. If you return p, then you return the address of arr.

The arr is an automatic local variable. It is allocated from stack memory when the function starts and deallocated the moment the function ends.

Your function returns an address to deallocated memory, whose content is undefined.
okay I got your point
If I replace double arr[3] by static double arr[3] I get the correct output.
What if you have to use it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
  const double *dp;
  dp = array(1.0, 2.0);

  const double *ee;
  ee = array(7.0, 4.2);

  for ( int i=0; i<3; ++i) {
    std::cout << "dp[" <<i << "]= " <<dp[i] << '\n';
  }
  return 0;
}
Topic archived. No new replies allowed.