如何从 C 中的函数返回多个值? [英] How do I return multiple values from a function in C?

查看:31
本文介绍了如何从 C 中的函数返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个函数产生结果 int 和结果 string,我如何从函数中返回它们?

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 only return one thing, as determined by the type preceding the function name.

推荐答案

我不知道你的 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.

这篇关于如何从 C 中的函数返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆