2011-02-27 47 views
2

我試圖將變量從一個功能傳遞給另一個。傳遞和返回變量在C

例如像:

FuncA的行:取入來自用戶的3個輸入,我想在FuncB使用這些3個輸入。

我該怎麼做?我只需從FuncA返回3個值,並將其作爲Func B的參數傳遞?

我會這樣做嗎? **不使用指針。

int FuncA(void); 
int FuncB(int A, int B, int C, int D, int E); 

int main(void) 
{ 
    FuncA(void); 
    FuncB(A,B,C); 
} 

int FuncA(void) 
{ 
    printf("Enter 3 number:"); 
    scanf("%d %d %d" &A, &B, &C); 
    return A, B, C; 
} 

int FuncB(int A, int B, int C) 
{ 
    ............. 
} 
+3

'返回A,B,C;'將只返回'C'值。逗號表達式的左側操作數不起作用。 – Mahesh

回答

7

首先,你只return一個可以爲每個函數值。這可能會讓你問,「如何從FuncA獲取A,B和C的值?」

你對指針有多少了解?如果你沒有牢牢掌握什麼是指針以及它們是如何工作的,那麼解決方案將很難理解。

解決方法是傳遞3個指針(一個用於A,B和C),以便FuncA可以爲它們分配一個值。這不使用return關鍵字。它在存儲器中的特定位置,其是,A,B,和C.

int FuncA(int* A, int* B, int* C) 
{ 
    printf("Enter 3 number:"); 
    scanf("%d %d %d", A, B, C); 
} 

分配值現在A,B和C包含用戶輸入,我們可以通過這些值來FuncB。你最終的代碼應該是這樣的:

int FuncA(int* A, int* B, int *C); 
int FuncB(int A, int B, int C); 

int main(void) 
{ 
    int A; 
    int B; 
    int C; 

    FuncA(&A, &B, &C); 
    FuncB(A, B, C); 
} 

int FuncA(int* A, int* B, int* C) 
{ 
    printf("Enter 3 number:"); 
    scanf("%d %d %d", A, B, C); 
} 

int FuncB(int A, int B, int C) 
{ 
    // ... 
} 
0

FuncA返回一個int。假設你想用A,B,C參數a調用FuncB並返回給FuncA的調用者,無論FuncB返回什麼,你都想要這樣的東西。

int FuncA(void) 
{ 
printf("Enter 3 number:"); 
scanf("%d %d %d" &A, &B, &C); 
return FuncB(A, B, C); 
} 
+0

如果FuncB有前一個參數,它還會返回FuncB(A,B,C)嗎? –

4

我會設置你的系統是這樣的:

void FuncA(int *A, int *B, int *C); 
int FuncB(int A, int B, int C); 

int main(void) 
{ 
    // Declare your variables here 
    int A, B, C; 
    // Pass the addresses of the above variables to FuncA 
    FuncA(&A, &B, &C); 
    // Pass the values to FuncB 
    FuncB(A, B, C); 
} 

void FuncA(int *A, int *B, int *C) 
{ 
    printf("Enter 3 numbers: "); 
    fflush(stdout); 
    scanf("%d %d %d", A, B, C); 
} 

int FuncB(int A, int B, int C) 
{ 
    //... 
} 
-3

聲明,B和C爲全局變量:

int A, B, C; 
int FuncA(void); 
int FuncB(int A, int B, int C); 
.... 

,並從任何函數訪問它們,無論是參數還是不行。或者聲明它們是靜態全局變量來限制全局範圍的可能損害。

+2

全局變量被認爲是不好的,http://stackoverflow.com/questions/484635/are-global-variables-bad。 – hlovdal

5

一種方法:

typedef struct { 
    int a; 
    int b; 
    int c; 
} ABC; 

ABC funcA(void); 
{ 
    ABC abc; 
    printf("Enter 3 numbers: "); 
    fflush(stdout); 
    scanf("%d %d %d", &abc.a, &abc.b, &abc.c); 
    return abc; 
} 

void funcB1(ABC abc) 
{ 
    ... 
} 

void funcB2(int a, int b, int c) 
{ 
    ... 
} 

int main(void) 
{ 
    funcB1(funcA()); // one alternative 

    ABC result = funcA(); // another alternative 
    funcB2(result.a, result.b, result.c); 
    ... 
}