且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 C 中的函数返回多个值?

更新时间:2023-02-23 08:40:50

我不知道你的 string 是什么,但我假设它管理自己的内存.

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:返回一个 struct ,其中包含您需要的所有类型.

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:使用指针传递值.

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.