I'm confused about how to get several float arrays from a class using return parameters. Here's a simplified example.
class Points
{
private:
float *x;
float *y;
float *z;
public:
void getCoordinates (float *retx, float *rety, float *retz);
}
void Points:: getCoordinates (float *retx, float *rety, float *retz)
{
retx=x;
rety=y;
retz=z;
}
When I make the assignment inside the function, the pointer values match. However, the values change as soon as I leave the function. Is the scope of the pointer somehow limited?
Based on How to properly return an array (class member) in C++?, I don't think that should be the case. The discussion suggests that not only is it possible to pass the pointer, but that the changes to memory via the pointer will effect the original instance of the class. Exactly how I would expect pointers to work.
One work around that I've tried is to use memcpy
void Points::getCoordinates (float *retx, float *rety, float *retz)
{
memcpy(retx, x, sizeof(float)*numPoints);
memcpy(rety, y, sizeof(float)*numPoints);
memcpy(retz, z, sizeof(float)*numPoints);
}
This works the way I want it too. The downside of this approach is that I need to allocate the correct amount of memory in the calling function, and I'm using more memory than I think I need to.