return a pointer to the first element of a dynamically allocated (c-style) array

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.
create another function(something like a destructor) to deallocate space.i think tht should so it.
Yeh I'd agree.
In my opinion, you basically have two choices of how to call delete[]. You'll have to move the out pointer out of func to make it visible to your delete[] function, or.... assign the return value of func to a local variable in main (don't pass it straight into strcpy) and use that variable in strcpy. Then call the delete[] function with that local variable from main.

Bertha
Last edited on
Thanks a lot for suggestions, in fact what I am going to do is, as Bertha pointed out, assign the return value of the function to a local variable in main and then call delete on it (logically it will point to the same data as the "out" variable that is returned from the function).

Don't know why it hasn't occured to me before, but, oh well, we live and learn - you can't see me complaining here.

Thanks again, everyone.
Topic archived. No new replies allowed.