trying to get two 'char *' back from a function

urucan
urucan used Ask the Experts™
on
If a function is already returning a 'char *' how can I get another 'char *' back from the function.  I want to pass in another 'char *' but I may not know the size of it before I pass it in to the calling function.  How can I achieve this?

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Pass parameters "by reference" like this:
Remember: Do not pass back references to local variable's that are on the function's stack. The data pointers will be invalid when control returns to the caller.

#include <string.h>
#include <stdio.h>

char *
myfunc(char **result2, char **result3)
{
  *result2 = "Hello";
  *result3 = "world";
  return "Three strings returned";
}

char *
badfunc(char **result2, char **result3)
{
  char localData[100] = "this data is on the stack";

  *result2 = localData; // <<<< do not do this
  *result3 = localData; // <<<< or this
  return localData;     // <<<< or this
}

int
main(int argc, char *argv[])
{
  char *r1;
  char *r2;
  char *r3;

  r1 = myfunc(&r2,&r3);

  printf("r1=[%s]\nr2=[%s]\nr3=[%s]\n",r1,r2,r3);
  return 0;
}

Author

Commented:
Thank you.  You answered my question well.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial