How to return multiple values from a function in C

4 Answers

0 votes
// Use Pointers

#include <stdio.h>

void function(int *a, int *b, int *c) {
    *a = 12;
    *b = 98;
    *c = 375;
}

int main(void) {
    int x, y, z;
    
    function(&x, &y, &z);

    printf("x = %d\n", x);
    printf("y = %d\n", y);
    printf("z = %d\n", z);
    
    return 0;
}



/*
run:

x = 12
y = 98
z = 375

*/

 



answered Dec 26, 2020 by avibootz
edited May 1 by avibootz
0 votes
#include <stdio.h>

// Return a Struct (

typedef struct {
    int a;
    int b;
} Pair;

Pair getPair() {
    Pair p;
    p.a = 10;
    p.b = 20;
    return p;
}

int main() {
    Pair result = getPair();
    
    printf("a = %d, b = %d\n", result.a, result.b);
    
    return 0;
}



/*
run:

a = 10, b = 20

*/

 



answered May 1 by avibootz
0 votes
#include <stdio.h>

// Use Output Parameters + Return Status

int compute(int x, int *out1, int *out2) {
    if (x < 0) return -1; // error
    *out1 = x + 1;
    *out2 = x * 2;
    
    return 0; // success
}

int main(void) {
    int x = 5;
    int a, b;

    int result = compute(x, &a, &b);

    if (result == 0) {
        printf("Success!\n");
        printf("out1 = %d\n", a);
        printf("out2 = %d\n", b);
    } else {
        printf("Error: x was negative\n");
    }

    return 0;
}


/*
run:

Success!
out1 = 6
out2 = 10

*/

 



answered May 1 by avibootz
0 votes
#include <stdio.h>

// Return Dynamically Allocated Memory

#include <stdio.h>
#include <stdlib.h>

int* getArray() {
    int *arr = malloc(3 * sizeof(int));
    if (arr == NULL) {
        return NULL; // allocation failed
    }
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    
    return arr;
}

int main(void) {
    int *arr = getArray();

    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    printf("Array values:\n");
    for (int i = 0; i < 3; i++) {
        printf("%d\n", arr[i]);
    }

    free(arr);
    return 0;
}


/*
run:

Array values:
1
2
3

*/

 



answered May 1 by avibootz
...