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

标签 c

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/

相关文章:

c - 如何在 C 中使用等待

c - Polarssl - 当输入特殊字符时,SHA1 给出不同的结果

c程序在循环程序时重复游戏的尝试

c - 如何在 Asterisk 中将 PostgreSQL 数据库时间戳更新为空?

c - 解释一下输出。它正在打印每个字母表的下一个字母表

c - 二进制 char 数组的补码

c++ - 通常使用什么方法来检测时间情况?

c - 如何在 C 程序中嵌套函数?

c - 使用 C 进行位掩码和位操作

c - 如何展示更好的平均水平?