• C

How to pass back to caller function location of reallocated arrays?



Hi All,

I want to write a C function that takes in input two arrays, may do some memory re-allocation, put some data into them and return the pointers to the two (possibly moved) arrays so that they are available to the calling function. The prototype should be like:

AddItemToArrays(char * Array1, char * Array2, char * Item1, char * Item2);

The problem I have is that when the Array1 and Array2 need to be re-allocated, the memory location will change and I am not sure how best to set this up so that the calling function will know about the new locations.

can you suggest what's the best way to do this?

Thanks,
Stefano
sdamianoAsked:
Who is Participating?
 
PaulCaswellCommented:
Hi sdamiano,

The normal way to deal with this situation is to pass pointers to the pointers or put both in a struct and pass a pointer to the struct.

AddItemToArrays(char * Array1, char * Array2, char * Item1, char * Item2);

becomes

AddItemToArrays(char ** Array1, char ** Array2, char * Item1, char * Item2);

or perhaps

typedef struct ArrayPair
{
  char * array1;
  char * array2;
} ArrayPair;

AddItemToArrays(ArrayPair * pair, char * Item1, char * Item2);

or even perhaps:

AddItemToArrays(ArrayPair * pair, ArrayPair item);

Paul
0
 
sdamianoAuthor Commented:
Hi Paul,

ok, that's what I did, it took me a little while to figure out how to deal with the double pointers, but it's working well now.

Thanks,
Stefano
0
 
PaulCaswellCommented:
Hi sdamiano,

They're quite tricky 'till you get your head around them. :-)

Have a good day!

Paul
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.