Michael Zelensky
Michael Zelensky

Reputation: 3

c function and multiple value returning

My question is in general how to use pointers in functions correctly.

if to be more specific I need to write a function the recives 3 values from a user and then retruns it to the main one for further actions. This is the code I have written so far:

#include <stdio.h>
#include <conio.h>

int inputThree(int, int, int);

int sortTwo(int, int);

int sortThree(int, int);

int main()

{

    int a=0, b=0, c=0;
    printf("before: func %d \n", b);
    inputThree(a,b,c);
    printf("after func: %d%d%d \n",a,b,c);
    getch();

}

int inputThree(int a, int b, int c)

{

    printf("Input three integers values: \n");
    scanf("%d%d%d", &a, &b, &c);
    return 0;

}

I'm intersted in understanding how to keep the values of scanf via pointers. When I return to the main function they are lost because they aren't global...

Also, I couldn't leave the function inputthree without parameters even though I want it to get them from scanf itself, so I had to put some values for it to run.

thanks in advance!

Upvotes: 0

Views: 74

Answers (3)

user1788956
user1788956

Reputation:

You can either return a struct or make a function that handles passed pointers as argument.

#include <stdio.h>

struct Foo{
    int x;
    int y;
};

//one way
struct Foo do_work();

//or another
void do_work(int *x, int *y);


int main(void) {

    return 0;
}

struct Foo do_work(){
//e.g.
    struct Foo foo;
    foo.x = 1;
    foo.y = 2;
    return foo;
}

void do_work1(int *x, int *y){
//e.g
    *x = 1;
    *y = 1;
}

Upvotes: 0

Retro Gamer
Retro Gamer

Reputation: 1112

Technically, only 1 thing (or none) can be returned from a function at a time. If you wanted to change the values of two or more variables via a function even after the function ends, you would need to pass into the function's parameters/arguments the memory reference of the variable.

Upvotes: -1

R Sahu
R Sahu

Reputation: 206597

Pass pointers to the variables from main to inputThree.

Change the function declaration.

int inputThree(int* aPtr, int* bPtr, int* cPtr);

Change the call.

inputThree(&a, &b, &c);

Change the implementation.

int inputThree(int* aPtr, int* bPtr, int* cPtr)
{
    printf("Input three integers values: \n");
    scanf("%d%d%d", aPtr, bPtr, cPtr);
    return 0;
}

Upvotes: 2

Related Questions