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

copying pointers into functions

This topic is 5175 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

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

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!


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

Share this post

Link to post
Share on other sites