sepiroth sepiroth - 3 years ago 223
C Question

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

If I have a function that produces a result

and a result
, how do I return them both from a function?

As far as I can tell I can only return one thing, as determined by the type preceding the function name.

Answer Source

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
    *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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download