c - 指针或返回两个值打印

标签 c return-value precision key-value-store

我正在尝试编写获取 2 个值或返回一个值的函数。所以当我想使用函数时,我得到的值是我认为的地址

int function (int a, int *b, *c){
    int value;
    value=a*2; 
    (*b)=value/10;
    (*c)=value%10;
}

int main(void){
    int val1,p1,p2,rest1,rest2;
    val1=150;
    function(val1,&p1,&p2);
    rest1=p1*2+p2;
    rest2=p2;
    printf("%d m %d end %d"rest1,rest2,&p2);
}

我也考虑只返回一个

int funct2(int a){
    int array [2];
    int b=(65*a)/100;
    int c=b%1000;
    array[0]=b;
    array[1]=c;
    return array;
}

int main(void)
{
    int a=18;
    int array[2];
    array=funct2(a);
}

也不行。

那么我如何构建函数来获取 2 个值或将这 2 个值作为一个值.. 请帮忙

最佳答案

这是不正确的:

printf("%d m %d end %d",rest1,rest2,&p2);

作为最后一个参数,&p2 是一个int*(p2 的地址)但是格式说明符是一个 %d。更改为:

printf("%d m %d end %d", rest1, rest2, p2);

要返回两个 int,您可以定义一个 struct 并按值返回:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct int_pair
{
    int division_result, modulus_result;
};

struct int_pair function (const int a)
{
    const int value = a * 2;
    struct int_pair result;

    result.division_result = value / 10;
    result.modulus_result  = value % 10;

    return result;
}

int main()
{
    struct int_pair p = function(150);
    printf("%d %d\n", p.division_result, p.modulus_result);
    return 0;
}

如果 C99 function() 可以使用复合文字作为返回值:

struct int_pair function (const int a)
{
    const int value = a * 2;
    return (struct int_pair) { value / 10, value % 10 };
}

参见 http://ideone.com/8PFtHq用于演示。

关于c - 指针或返回两个值打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13962462/

相关文章:

c - 运行最小 OpenMP 程序时的非法指令

c - stdout 和 STDOUT_FILENO 的区别

c - 在 C 中执行查找表的最佳方法是什么?

c - 为什么我的函数总是返回 1?

c# - 是否可以在 C# 中返回对变量的引用?

C++返回对临时的引用

sql-server - EF Core 强制刷新数据库中的实体(强制从数据库获取值)

c - 强制 printf 显示确定的位数并删除剩余的 0

machine-learning - 分类报告中的精确率和召回率是如何计算的?

c++ - 在 C/C++ 中分配内存失败