How do I return multiple values from a function in C? How do I return multiple values from a function in C? c c

How do I return multiple values from a function in C?


I don't know what your string is, but I'm going to assume that it manages its own memory.

You have two solutions:

1: Return a struct which contains all the types you need.

struct Tuple {    int a;    string b;};struct Tuple getPair() {    Tuple r = { 1, getString() };    return r;}void foo() {    struct Tuple t = getPair();}

2: Use pointers to pass out values.

void getPair(int* a, string* b) {    // Check that these are not pointing to NULL    assert(a);    assert(b);    *a = 1;    *b = getString();}void foo() {    int a, b;    getPair(&a, &b);}

Which one you choose to use depends largely on personal preference as to whatever semantics you like more.


Option 1: Declare a struct with an int and string and return a struct variable.

struct foo {     int bar1; char bar2[MAX];};struct foo fun() { struct foo fooObj; ... return fooObj;}

Option 2: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:

int fun(char **param) { int bar; ... strcpy(*param,"...."); return bar;}

or

 char* fun(int *param) { char *str = /* malloc suitably.*/ ... strcpy(str,"...."); *param = /* some value */ return str;}

Option 3: Similar to the option 2. You can pass both via pointer and return nothing from the function:

void fun(char **param1,int *param2) { strcpy(*param1,"...."); *param2 = /* some calculated value */}


Since one of your result types is a string (and you're using C, not C++), I recommend passing pointers as output parameters. Use:

void foo(int *a, char *s, int size);

and call it like this:

int a;char *s = (char *)malloc(100); /* I never know how much to allocate :) */foo(&a, s, 100);

In general, prefer to do the allocation in the calling function, not inside the function itself, so that you can be as open as possible for different allocation strategies.