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

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

问题描述

如果我有一个产生结果 INT 和结果字符串函数,我怎么回报他们都从功能?

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

据我可以告诉大家,我只能回一件​​事,由式preceding函数名确定的。

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

推荐答案

我不知道你的字符串是的,但我会认为它管理的是什么它自己的内存。

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

您有两种解决方法:

1:返回一个结构它包含了所有你需要的类型。

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

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);
}

您选择使用哪一个个人的preference很大程度上取决于以任何语义您想了解更多。

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

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

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