开发者

returning multiple values from a function [duplicate]

开发者 https://www.devze.com 2023-01-18 08:57 出处:网络
This question already has answers here: How do I return multiple values from a function in C? (8 answers)
This question already has answers here: How do I return multiple values from a function in C? (8 answers) Closed 3 years ago.

Can anyone tell me how to retu开发者_JS百科rn multiple values from a function?

Please elaborate with some example?


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;
}


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;
}


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:

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 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 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:

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.


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;
}


You cannot return multiple values from a C function. You can either

  1. Return a data structure with multiple values, like a struct or an array.
  2. 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


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;
 }

}


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:

#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;

}


Method 1 is using array

Method 2 is using pointer

Method 3 is using structure

0

精彩评论

暂无评论...
验证码 换一张
取 消