Tha*_*yen 2 c parameter-passing
我正在尝试将变量从一个函数传递到另一个函数.
例如:
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)
{
.............
}
Run Code Online (Sandbox Code Playgroud)
首先,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);
}
Run Code Online (Sandbox Code Playgroud)
既然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)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
一种方法:
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);
...
}
Run Code Online (Sandbox Code Playgroud)