Archived

This topic is now archived and is closed to further replies.

CProgrammer

copying pointers into functions

Recommended Posts

I have a recursive function and one of the arguments is a pointer because i dont know its size on compile time. How can i copy the pointer into the function when i call it again. -CProgrammer [edited by - CProgrammer on October 12, 2003 8:56:26 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
What?

Please explain what you mean, as I can''t understand what you are asking.

Share this post


Link to post
Share on other sites
Ok ill try to be more precise.
I have a recursive function which has a pointer as argument.
Something like this:
void somefunc(int *pointer)
{
do some stuff
//call itself
somefunc(pointer); //here pointer should be copied
//meaning all the content of the array pointer
//should be copied into the next function

do some stuff
somefunc(...);
...
}

Now as mentioned when the function calls itself it should pass
the pointer on but copy its content into the next function.
How?

Share this post


Link to post
Share on other sites
What are you trying to do? This means you need to allocate memory on every step of your algorithm. This is indeed doable but is very badly designed, and I'm pretty sure there are other, faster and easier, ways around it. Anyway, there you go:


void somefunc( int * pointer, long arraylength ) {

//do stuff
int * newpointer = (int*)malloc( arraylength * sizeof(int) );
for( int i = 0; i < arraylength; ++i )
newpointer[ i ] = pointer[ i ];
//do stuff
somefunc( newpointer, arraylength );
//do stuff
free( newpointer );
}


This will create a new area in memory, copy the contents of the previous array into the new array, and give a pointer of this new array to the next call of the function. But it's ugly, adds memory allocation overhead (the C/C++ memory managers are quite slow) and an O(n) copy overhead. I strongly advise you find another way of doing it.

EDIT : someone remove this [ i ] italics tag support!! or change it to something else!

ToohrVyk



[edited by - ToohrVyk on October 12, 2003 9:57:07 AM]

Share this post


Link to post
Share on other sites