gpt4 book ai didi

c - 在 C 中传递和返回变量

转载 作者:行者123 更新时间:2023-12-04 11:13:34 24 4
gpt4 key购买 nike

我试图将变量从一个函数传递到另一个函数。

例如:

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)
{
.............
}

最佳答案

首先,您只能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)
{
// ...
}

关于c - 在 C 中传递和返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5130978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com