簡體   English   中英

如何在C中返回三個數字而不使用C中的數組或指針?

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

問題:

編寫一個接受三個整數的程序,然后按順序打印並反轉。 使用三個功能,一個用於讀取數據,一個用於按順序讀取它們,另一個用於以相反順序打印。

該計划(未完成):

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

錯誤:錯誤:'x'未聲明(首次在此函數中使用)| 注意:每個未聲明的標識符僅針對它出現的每個函數報告一次 錯誤:'y'未聲明(首次使用此功能)| 錯誤:'z'未聲明(首次在此函數中使用)|

如何修改此程序,以便我可以在不使用數組或指針的情況下返回三個變量? 或者不使用那些是不可能的?

您可以創建包含這三個值的結構

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

然后向函數傳遞一個指向結構實例的指針(旁注:總是用指針執行此操作,因為它更有效,因為它只傳遞一個8字節的值。傳遞結構本身意味着(如果我沒記錯)編譯器將結構作為參數傳遞時,會嘗試將結構拆分為它的值

擴大我的評論。 不是合理的代碼,在實踐中不推薦 ,但它是修改代碼以實現多個返回值的要求而無需數組或指針(或結構)的一種方法。

#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