c - 如何让一个函数返回多个值?

标签 c

<分区>

struct r() {
    return 1, "hello";
}

int main() {

    int x;
    char y[100];
    x, y = r(); // set x to int 1, and set y to "hello"

}

无论如何我可以做到这一点吗?我相信这在 C 中是可能的

最佳答案

是的,您可以使用可能包含任意数据字段的结构来执行此操作,如以下完整程序所示:

#include <stdio.h>

struct tPair {int one; int two;};

struct tPair returnPair(void) {
    struct tPair plugh;
    plugh.one = 7;
    plugh.two = 42;
    return plugh;
}

int main(void) {
    struct tPair xyzzy = returnPair();
    printf("Pair is %d, %d\n", xyzzy.one, xyzzy.two);
    return 0;
}

如果你编译并运行它,你会看到:

Pair is 7, 42

关于c - 如何让一个函数返回多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49062063/

相关文章:

c - 向结构数组添加新条目会覆盖所有最后的条目

计算机断层扫描 : Matlab to C/OpenCV code conversion error

c - LLVM 字符串输入/输出

c++ - 在两个共享对象之间共享变量

比较 int 和 size_t

c - 为什么在打印一行文件时光标会转到下一行?

c - 中缀到带空格的后缀

c - 有没有办法使用 CUPS 库获取打印机的字节命令列表?

c - 将稀疏查找表映射到微 Controller 上 C 中的函数指针数组

c++ - 为什么我的变量在 WaitForSingleObject 之后没有保持状态?