MrCWizard
asked on
Return float array with function
I'm writing an program and one of the functions I'm writing have to return a float array but I'm having a heck of a time figuring out how to put this work.
Can you help me?
Here's the example:
float *GetPoints()
{
float p[3];
scanf("%f %f %f", p[0], p[1], p[2]);
return p;
}
void main(void)
{
float point[3];
point = GetPoints();
}
Can you help me?
Here's the example:
float *GetPoints()
{
float p[3];
scanf("%f %f %f", p[0], p[1], p[2]);
return p;
}
void main(void)
{
float point[3];
point = GetPoints();
}
what you are doing in GetPoints function is returning a pointer to a local variable allocated on stack
so when function finishes the memory pointed by return value is garbage
you should do it that way:
void GetPoints(float p[3])
{
scanf("%f %f %f", p[0], p[1], p[2]);
}
void main(void)
{
float point[3];
GetPoints(point);
}
so when function finishes the memory pointed by return value is garbage
you should do it that way:
void GetPoints(float p[3])
{
scanf("%f %f %f", p[0], p[1], p[2]);
}
void main(void)
{
float point[3];
GetPoints(point);
}
ASKER
OK guys, that made it clear for now. Thank you very mutch.
the solution works but the reason for failure is different. you cannot assign a value to an array. in C/C++ pointers are no different than arrays except that arrays point to a fixed location. once you create an array you cannot assign it a new value. "point = GetPoints()" does exactly that and your code won't compile.
Hi x-pander,
> scanf("%f %f %f", p[0], p[1], p[2]);
Careful:
scanf("%f %f %f", &p[0], &p[1], &p[2]);
And also be aware that there is no guarantee someon using your function really passes three floats. Better wrap them up, and pass heap memory, and use doubles:
double *GetPoints()
{
double* p;
p=(double*)malloc(3*sizeof (double));
scanf("%f %f %f", &p[0], &p[1], &p[2]);
return p;
}
Just make sure you call free() later.
Cheers!
Stefan
> scanf("%f %f %f", p[0], p[1], p[2]);
Careful:
scanf("%f %f %f", &p[0], &p[1], &p[2]);
And also be aware that there is no guarantee someon using your function really passes three floats. Better wrap them up, and pass heap memory, and use doubles:
double *GetPoints()
{
double* p;
p=(double*)malloc(3*sizeof
scanf("%f %f %f", &p[0], &p[1], &p[2]);
return p;
}
Just make sure you call free() later.
Cheers!
Stefan
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Yes, it's normally not "just three points", but they represent something (e.g., 3D coordinates, the size of each of the 3 stooges in inches,... etc.)
Wrap'em, give them a nice & descriptive name, and use them accordingly.
Wrap'em, give them a nice & descriptive name, and use them accordingly.
void GetPoints(p)
float *p;
{
scanf("%f %f %f", p, p + 1, p + 2);
}
int main(void)
{
float point[3];
GetPoints(point);
printf("%f %f %f\n", point[0], point[1], point[2]);
return 0;
}