Can anyone tell me how to return multiple values from a function?
Please elaborate with some example?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
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.
or:
You cannot return multiple values from a C function. You can either
Your choices here are to either return a struct with elements of your liking, or make the function to handle the arguments with pointers.
To return multiple values from a function we should use a pointer. Here is an example through which you can understand it better
}
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 value of that composite type:
Do not define 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 operationally related (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 thestrtod()
andstrtol()
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:You can combine these approaches; here's an example inspired by some work I'm currently doing:
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.
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.
Here is my code: