tags:

views:

105

answers:

3

Hi Guys,

Im trying to create an array of tm* structs, and then return them at the end of the function. This is what i have at the moment:

struct tm* BusinessLogicLayer::GetNoResponceTime()
 {
   struct tm* time_v[3];
   struct tm* time_save;
   int s = 3;
   time_save = LastSavedTime();
   time_v[0] = time_save;
   sleep(5);
   time_save = LastSavedTime();
   time_v[1] = time_save;
   sleep(5);
   time_save = LastSavedTime();
   time_v[2] = time_save;

   return time_v;
 }

I understand that given the code i have now it will not be possible to return the array, because it will be destroyed when the function ends. Can anyone help me with regards to how i would go about being able to access the array from the returned value after the function has ended?

Regards

Paul

+4  A: 

Either allocate the array on the heap, but you will need to remember to delete[] the array when you have finished using it.

tm* time_v = new tm[3];

Or as this is C++, a better option would be to use a vector

std::vector<tm> time_v(3);

The vector itself is allocated on the stack but it holds an array which is allocated on the heap. When you copy the vector (for instance returning it) the contents of the underlying array are also copied.

You could also simplify the function by not using the temp variable time_save

time_v[0] = *LastSavedTime();
sleep(5);

time_v[1] = *LastSavedTime();
sleep(5);

time_v[2] = *LastSavedTime();

The C style struct declarations are also not required in C++

struct tm* time_v[3];

//should be
tm* time_v[3];
Yacoby
Shouldn't that have been `std::vector<tm*> time_v(3);` and ditto for the `new` variant?
Andreas Brinck
this seems okay to me
Elemental
@Andreas That depends on far more than the code sample given, however I would suspect from the fact that it seems to be a time that it shouldn't be a problem not using pointers.
Yacoby
@Yacoby @Elemental From the original question: "Im trying to create an array of tm*". Also the function `LastSavedTime` seems to return `tm*`. This can all be changed of course.
Andreas Brinck
Ignore the return type, as im pretty sure its wrong. Im not sure how i would define what an array of tm* looks like...
paultop6
+4  A: 

Create a copy and return that instead:

vector<tm> ret;
struct tm* time_save;

time_save = LastSavedTime();
ret.push_back(*time_save);

Sleep(5);
time_save = LastSavedTime();
ret.push_back(*time_save);

Sleep(5);
time_save = LastSavedTime();
ret.push_back(*time_save);

return ret;

You'll need to change the signature, obviously.

John Dibling
A: 

Sorry Paul, in a slight hurry, however try this ...

   struct tm* time_v = new struct tm[ 3 ]; 

This will allocate the structures for you, and you then would initialize them and return as per the code you supplied in the function.

I would however remind you that once it's not needed, please free the memory using 'delete'

Hope this helps - Neil

Neil