Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

c - returning multiple values from a function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...