C语言 从函数返回多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3829167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
returning multiple values from a function
提问by Shweta
Can anyone tell me how to return multiple values from a function?
Please elaborate with some example?
谁能告诉我如何从函数返回多个值?
请举例说明?
回答by nperson325681
Your choices here are to either return a struct with elements of your liking, or make the function to handle the arguments with pointers.
您在这里的选择是要么返回一个包含您喜欢的元素的结构,要么让函数用指针来处理参数。
/* method 1 */
struct Bar{
int x;
int y;
};
struct Bar funct();
struct Bar funct(){
struct Bar result;
result.x = 1;
result.y = 2;
return result;
}
/* method 2 */
void funct2(int *x, int *y);
void funct2(int *x, int *y){
/* dereferencing and setting */
*x = 1;
*y = 2;
}
int main(int argc, char* argv[]) {
struct Bar dunno = funct();
int x,y;
funct2(&x, &y);
// dunno.x == x
// dunno.y == y
return 0;
}
回答by Oliver Charlesworth
You can't do that directly. Your options are to wrap multiple values into a struct, or to pass them in as pointer arguments to the function.
你不能直接这样做。您的选择是将多个值包装到一个结构中,或者将它们作为指针参数传递给函数。
e.g.
例如
typedef struct blah
{
int a;
float b;
} blah_t;
blah_t my_func()
{
blah_t blah;
blah.a = 1;
blah.b = 2.0f;
return blah;
}
or:
或者:
void my_func(int *p_a, float *p_b)
{
*p_a = 1;
*p_b = 2.0f;
}
回答by John Bode
First of all, take a step back and ask why you need to return multiple values. If those values aren't somehow related to each other (either functionally or operationally), then you need to stop and rethink what you're doing.
首先,退一步问问为什么需要返回多个值。如果这些价值观在某种程度上彼此不相关(无论是在功能上还是在操作上),那么您需要停下来重新思考您在做什么。
If the various data items are part of a larger, composite data type (such as a mailing address, or a line item in a sales order, or some other type described by multiple attributes), then define a struct type to represent a single valueof that composite type:
如果各种数据项属于更大的复合数据类型(例如邮寄地址或销售订单中的行项目,或由多个属性描述的其他类型),则定义结构类型来表示单个值该复合类型的:
struct addr { // struct type to represent mailing address
char *name;
int streetNumber;
char *streetName;
char *unitNumber;
char *city;
char state[3];
int ZIP;
};
struct addr getAddressFor(char *name) {...}
struct point2D {
int x;
int y;
};
struct polygon2D {
size_t numPoints;
struct point2D *points;
};
struct point2D getOrigin(struct polygon2D poly) {...}
Do notdefine a struct to collect random items that aren't somehow related to each other; that's just going to cause confusion for you and anyone who has to maintain your code down the road.
千万不能定义一个结构来收集未以某种方式相互关联的随机物品; 这只会给您和任何必须维护您的代码的人造成混乱。
If the data items are not functionally related, but are somehow operationallyrelated (e.g. data plus a status flag plus metadata about the operation or items as part of a single input operation), then use multiple writable parameters. The most obvious examples are the *scanf()functions in the standard library. There are also the strtod()and strtol()functions, which convert a string representation of a number; they return the converted value, but they also write the first character that was not converted to a separate parameter:
如果数据项在功能上不相关,但在某种程度上与操作相关(例如,数据加上状态标志加上有关操作的元数据或作为单个输入操作的一部分的项目),则使用多个可写参数。最明显的例子是*scanf()标准库中的函数。还有strtod()和strtol()函数,它们转换数字的字符串表示形式;它们返回转换后的值,但它们也会写入未转换为单独参数的第一个字符:
char *str = "3.14159";
double value;
char *chk;
value = strtod(str, &chk);
if (!isspace(*chk) && *chk != 0)
printf("Non-numeric character found in %s\n", str);
You can combine these approaches; here's an example inspired by some work I'm currently doing:
您可以结合使用这些方法;这是一个受我目前正在做的工作启发的示例:
typedef enum {SUCCESS, REQ_GARBLED, NO_DATA_OF_TYPE, EMPTY, ERROR} Status;
typedef struct bounds {...} Bounds;
tyepdef struct metadata {
size_t bytesRead;
size_t elementsRead;
size_t rows;
size_t cols;
} Metadata;
typedef struct elevations {
size_t numValues;
short *elevations;
} Elevations;
Elevations elevs;
Metadata meta;
Bounds b = ...; // set up search boundary
Status stat = getElevationsFor(b, &elevs, &meta);
The service that I request elevation data from returns a 1-d sequence of values; the dimensions of the array are returned as part of the metadata.
我从中请求高程数据的服务返回一维值序列;数组的维度作为元数据的一部分返回。
回答by Michael Foukarakis
You can do it using structures:
您可以使用结构来做到这一点:
#include <stdio.h>
struct dont { int x; double y; };
struct dont fred(void)
{
struct dont b;
b.x = 1;
b.y = 91.99919;
return b;
}
int main(int argc, char **argv)
{
struct dont look = fred();
printf("look.x = %d, look.y = %lf\n", look.x, look.y);
return 0;
}
回答by arbithero
You cannot return multiple values from a C function. You can either
不能从 C 函数返回多个值。你可以
- Return a data structure with multiple values, like a struct or an array.
- Pass pointers to the function and modify the values of the pointers inside the function. You need to pass x number of pointers where x is the number of return values you need
- 返回具有多个值的数据结构,如结构或数组。
- 将指针传递给函数并修改函数内部指针的值。您需要传递 x 个指针,其中 x 是您需要的返回值的数量
回答by sumit
To return multiple values from a function we should use a pointer. Here is an example through which you can understand it better
要从函数返回多个值,我们应该使用指针。这是一个示例,通过它您可以更好地理解它
int* twoSum(int* nums, int numsSize, int target) {
int i,j,*a;
a=(int*)malloc(2*sizeof(int));
for(i=0;i<numsSize;i++)
for(j=i+1;j<numsSize;j++)
if(nums[i]+nums[j]==target)
{
a[0]=i;
a[1]=j;
return a;
}
}
}
回答by Luca
I′m a beginner in C, so I don′t have experience with array, pointer, structure. To get more than one value from my function I just used a global variable.
我是 C 初学者,所以我没有数组、指针、结构方面的经验。为了从我的函数中获取多个值,我只使用了一个全局变量。
Here is my code:
这是我的代码:
#include <stdio.h>
double calculateCharges( double hourCharges );
// Global variable for totalCharges-function and main-function interaction
double totalCharges = 0;
int main ( void ) {
double car1 = 0;
double car2 = 0;
double car3 = 0;
double totalHours = 0;
printf( "%s", "Hours parked for Car #1: ");
scanf( "%lf", &car1 );
printf( "%s", "Hours parked for Car #2: ");
scanf( "%lf", &car2 );
printf( "%s", "Hours parked for Car #3: ");
scanf( "%lf", &car3 );
totalHours = car1 + car2 + car3;
printf( "%s", "Car\tHours\tCharge\n");
printf( "#1\t%.1f\t%.2f\n", car1, calculateCharges( car1 ));
printf( "#2\t%.1f\t%.2f\n", car2, calculateCharges( car2 ));
printf( "#3\t%.1f\t%.2f\n", car3, calculateCharges( car3 ));
printf( "TOTAL\t%.1f\t%.2f\n", totalHours, totalCharges);
}
double calculateCharges( double hourCharges ) {
double charges = 0;
if( hourCharges <= 3.0 ) {
charges = 2;
} else if ( hourCharges >= 24.0) {
charges = 10.00;
} else {
charges = ((hourCharges - 3.0)*0.5) + 2.0;
}
totalCharges += charges;
return charges;
}
回答by Akshaya Moorthy
Method 1 is using array
方法 1 使用数组
Method 2 is using pointer
方法二是使用指针
Method 3 is using structure
方法3是使用结构

