2011-02-27 42 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); 
    ... 
}