是否有可能将多个值从函数返回到main,以便我可以在main函数中单独使用。我需要在我正在开发的项目中使用这个概念。由于代码很大,我给出了一个显示我的要求的简单代码。
#include <stdio.h>
int func ()
{
int a[3] = { 31, 32, 33};
static int x, y, z;
char b[20];
x = a[0];
y = a[1];
z = a[2];
printf ("%d\n", x);
printf ("%d\n", y);
printf ("%d\n", z);
return 0;
}
int main()
{
int x, y, z ;
func ();
printf ("%d\n", x);
printf ("%d\n", y);
printf ("%d\n", z);
return 0;
}
我邀请多种解决方案,但请用正确的代码解释您的概念。感谢您的时间
答案 0 :(得分:4)
您可以使用结构。
#include <stdio.h>
struct data_t {
int x, y, z;
};
struct data_t func (void)
{
int a[3] = { 31, 32, 33};
struct data_t data;
data.x = a[0];
data.y = a[1];
data.z = a[2];
printf ("%d\n", data.x);
printf ("%d\n", data.y);
printf ("%d\n", data.z);
return data;
}
int main(void)
{
struct data_t data;
data = func ();
printf ("%d\n", data.x);
printf ("%d\n", data.y);
printf ("%d\n", data.z);
return 0;
}
使用指针的替代方法:
#include <stdio.h>
void func (int* x, int* y, int* z)
{
int a[3] = { 31, 32, 33};
*x = a[0];
*y = a[1];
*z = a[2];
printf ("%d\n", *x);
printf ("%d\n", *y);
printf ("%d\n", *z);
}
int main(void)
{
int x, y, z;
func (&x, &y, &z);
printf ("%d\n", x);
printf ("%d\n", y);
printf ("%d\n", z);
return 0;
}
答案 1 :(得分:0)
简单地说......你可以通过下面描述的许多方法来做到这一点: -
1)使用global variable
...但不是一个好的做法我会说上面的cmnt ......
2)在引用参数中使用和传递变量(即call by reference
)。 EX:
void f(int *p , int *q)
3)返回类型为array
...或structure
或union
。例如:
temp f(<the parameters here>);
我知道C不允许直接返回数组...因为你可以像下面这样做&#34;示例代码&#34;我在这里发帖
`
#include <stdio.h>
/* function to generate and return random numbers */
int * getRandom( ) {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
p = getRandom(); // this is the line where i want your attention to be
for ( i = 0; i < 10; i++ ) {
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
`
5)使用它们的混合混合物...... like returning a pointer of a structure
... passing argument as call by reference for a struct data type
...
答案 2 :(得分:-2)
int *func()
int a[3] = {31, 32, 33};
int x,y,z;
x = a[0];
y = a[1];
z = a[2];
printf ("%d\n", x);
printf ("%d\n", y);
printf ("%d\n", z);
return a;
}
int main()
{
int x, y, z;
int b[3];
b=func ();
printf ("x:%d\n", b[0]);
printf ("y:%d\n", b[1]);
printf ("z:%d\n", b[2]);
return 0;
}
I have not compiled this but I think it might help you.