我正在尝试编写获取 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/