I need a little clarification on the following matter - I need to create and modify a dynamically allocated character array inside a function and then return it to use whatever there is in it in the main function.
What I wrote looks more or less like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
char* func(...)
{
char* out=new char[array_length];
...
/* modify "out" here in one way or another */
...
return out;
}
int main()
{
...
strcpy(some_char_array,func(...));
return 1;
}
| |
Yes, from the first glance the above code works quite fine (and yes, it actually DOES work, I've tested it quite a number of times), although I have a couple of questions.
1. Since once the function returns a value and terminates, all the variables that were declared inside it get deallocated, don't I need to declare "out" as static (i.e. static char* out=new char[array_length])?
2. Well, obviously, as I allocate the memory for "out" in the function, I also need to free the memory using "delete". But I don't quite see where to do it (obviously, not before returning the pointer, but then again, surely can't do it after returning as well :P)
This concludes my query, I truly hope that someone will shed light on this question of mine.
p.s. I beg you not to suggest another ways of doing it - trust me, it must be done exactly as I've described it (otherwise I'd have to rewrite the whole program and it is quite long and not all of it is written by me, so no hope of modifying stuff there), I just need to get the memory allocation right, thats all.