gpt4 book ai didi

c - 从c中的另一个函数获取输出值

转载 作者:行者123 更新时间:2023-11-30 18:59:37 24 4
gpt4 key购买 nike

int assign(int *m){
//static int n = 9;
// m = &n; // will assign the value to the variable a = 9
*m = 10;
// int n =8;
// m = &n; // will fail as the scope of the variable is within the function
return 0;
}

int main(){
int a ;
assign(&a);
printf("%d",a);
return 0;
}

and: a= 10 有没有其他方法可以获取a中的输出(不传递地址并使用函数的指针和参数)

最佳答案

C 中的每个函数都允许返回单个值。

int assign(......)
^
|
output type

您可以使用return 关键字来执行此操作。返回某些内容的函数就像具有相同类型的任何其他表达式一样。

例如,如果您有:

int assign(void)
{
return 10;
}

以下所有内容均有效:

int a = assign();
int b = (assign()*20)-assign()/assign();

您可能需要在参数中使用指针的原因是有多个输出。

例如,采用一个遍历数组并返回最小值和最大值的函数:

void minmax(int *array, int size, int *minimum, int *maximum)
{
int i;
int min_overall = INT_MAX;
int max_overall = INT_MIN;
/* error checking of course, to make sure parameters are not NULL */
/* Fairly standard for: */
for (i = 0; i < size; ++i)
{
if (array[i] < min_overall)
min_overall = array[i];
if (array[i] > max_overall)
max_overall = array[i];
}
/* Notice that you change where the pointers point to */
/* not the pointers themselves: */
*minimum = min_overall;
*maximum = max_overall;
}

在你的main中,你可以像这样使用它:

int arr[100];
int mini, maxi;
/* initialize array */
minmax(arr, 100, &mini, &maxi);

编辑:既然您询问是否有其他方法可以做到这一点,这里有一个示例(尽管我绝对不推荐将其用于像您这样的用法):

struct assign_ret
{
int return_value;
int assigned_value;
};

struct assign_ret assign(void)
{
assign_ret ret;
ret.assigned_value = 10;
ret.return_value = 0;
return ret;
}

并在main中:

struct assign_ret result = assign();
if (result.return_value != 0)
handle_error();
a = result.assigned_value;

我不推荐这样做的原因是,struct 用于将相关的数据放置在一起。函数错误返回值与其数据输出无关。

关于c - 从c中的另一个函数获取输出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9823212/

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