简体   繁体   English

如何在C中返回三个数字而不使用C中的数组或指针?

[英]How to return three numbers in a function without using array or pointer in C?

The question: 问题:

Write a program that accepts three integers and then prints them in the order read and reversed. 编写一个接受三个整数的程序,然后按顺序打印并反转。 Use three functions, one to read the data, one to print them in the order read and one to print in reverse order. 使用三个功能,一个用于读取数据,一个用于按顺序读取它们,另一个用于以相反顺序打印。

The program (not finished): 该计划(未完成):

#include <stdio.h>

int accept(){
    int x, y, z;
    printf("Please enter three integers: \n");
    scanf("%d %d %d", &x, &y, &z);
    return x, y, z;
}

int main(){
    x, y, z = accept();
}

Errors: error: 'x' undeclared (first use in this function)| 错误:错误:'x'未声明(首次在此函数中使用)| note: each undeclared identifier is reported only once for each function it appears in| 注意:每个未声明的标识符仅针对它出现的每个函数报告一次 error: 'y' undeclared (first use in this function)| 错误:'y'未声明(首次使用此功能)| error: 'z' undeclared (first use in this function)| 错误:'z'未声明(首次在此函数中使用)|

How can I modify this program so that I can return the three variables without using arrays or pointers? 如何修改此程序,以便我可以在不使用数组或指针的情况下返回三个变量? Or is it impossible without using those? 或者不使用那些是不可能的?

You could create a struct that contains those three values 您可以创建包含这三个值的结构

typedef struct MyStruct
{
    int a, b, c;
} MyStruct;

Then pass a pointer to the struct instance to and from the function (side note: ALWAYS do this with a pointer as it is more efficient because it only passes an 8 byte value. Passing the struct itself means (if I remember correctly) the compiler will attempt to split the struct into it's values when passing it as an argument) 然后向函数传递一个指向结构实例的指针(旁注:总是用指针执行此操作,因为它更有效,因为它只传递一个8字节的值。传递结构本身意味着(如果我没记错)编译器将结构作为参数传递时,会尝试将结构拆分为它的值

Expansion of my comment. 扩大我的评论。 This is not sensible code and not recommended in practice but it is one way to amend your code to implement the requirement of multiple return values without arrays or pointers (or structs). 不是合理的代码,在实践中不推荐 ,但它是修改代码以实现多个返回值的要求而无需数组或指针(或结构)的一种方法。

#include <stdio.h>

int accept(char opt){
    /* static variables remember their values between calls */
    static int x, y, z;

    if (opt=='x') return x;
    if (opt=='y') return y;
    if (opt=='z') return z;

    /* any other value of opt, read in new values */
    printf("Please enter three integers: \n");
    return scanf("%d %d %d", &x, &y, &z);
}

int main(){
    int x, y, z;
    accept(' ');
    x = accept('x');
    y = accept('y');
    z = accept('z');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM