Function not returning correct values?
Hello,
the following code doesnot return the corect values to the main function. However it prints the correct values within the function. Also the same when written in C works absolutely fine. Pls tell me where im going wrong and correct me. U can run it and check!
Thanks
Prads
<code>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cmath>
#include <iomanip>
using namespace std;
float *calcloopcoef(float lbw,float zeta,float k);
int main()
{
float *arrt;
arrt=calcloopcoef(25,0.7,.25);
cout<<"The returned values are"<<endl<<arrt[0]<<endl<<arrt[1]<<endl;
getchar();
return 0;
}
float *calcloopcoef(float lbw,float zeta,float k)
{
float arrtau[2],wn;
wn=lbw*8*zeta/(4*pow(zeta,2)+1);
arrtau[0]=k/pow(wn,2);
arrtau[1]=(2*zeta)/wn;
cout<<"values within fn"<<endl<<arrtau[0]<<endl<<arrtau[1]<<endl;
return arrtau;
}
[1075 byte] By [
prads] at [2007-11-20 11:48:11]

# 1 Re: Function not returning correct values?
Within the function, arrtau is allocated on the stack. When the function returns, the pointer to it is no longer valid.
You have two options:
1) Allocate on the heap using new or malloc, and don't forget to free() or delete later. This is generally not recommended, since it's "nice" for things to be malloc'd and free'd at the same "level" of the program.
2) Pass in arrtau to the function as an argument, allocated however you like (stack or heap) in main(), and have the function return void. I suggest this.
# 4 Re: Function not returning correct values?
try this instead:
declare the arrt[2] array in main() and pass the address to the function so it can write the results there.
void calcloopcoef(float*arrtau, float lbw, float zeta, float k);
int main()
{
float arrt[2];
calcloopcoef(arrt, 25,0.7,.25);
cout<<"The returned values are"<<endl<<arrt[0]<<endl<<arrt[1]<<endl;
return 0;
}
void calcloopcoef(float*arrtau, float lbw, float zeta, float k)
{
float wn;
wn=lbw*8*zeta/(4*pow(zeta,2)+1);
arrtau[0]=k/pow(wn,2);
arrtau[1]=(2*zeta)/wn;
cout<<"values within fn"<<endl<<arrtau[0]<<endl<<arrtau[1]<<endl;
}