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

前端 未结 8 1020
深忆病人
深忆病人 2020-11-22 15:14

If I have a function that produces a result int and a result string, how do I return them both from a function?

As far as I can tell I can

8条回答
  •  抹茶落季
    2020-11-22 15:55

    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.

提交回复
热议问题