user133466
user133466

Reputation: 3415

return values from a struct

typedef struct Value{
    int id;
    char type;
    char a;
} Value;

void fooV(Value v){
    v.id = 10;
    v.type = 'L';
    v.a = 'R';
}

int main(void){
    Value v;
    Pointer p;
    int id = 5;
    char type = 't';
    char a = 'a';

    printf("id: %d, type: %c, a: %c \n",id,type,a);

    v.a = a;
    v.id = id;
    v.type = type;
    fooV(v);
    printf("id: %d, type: %c, a: %c \n",id,type,a);

}

on the fooV call, Local variable value is created ... therefore no data in the caller will be updated But what if I want to return the values from fooV? what should I add to fooV? Thanks

Upvotes: 2

Views: 1453

Answers (3)

James McNellis
James McNellis

Reputation: 355307

If you just want to have a fooV function that returns a "constructed" Value struct, you can rewrite fooV as follows:

Value fooV() {
    Value v;
    v.id = 10;
    v.type = 'L';
    v.a = 'R';
    return v;
}

and you would call this function like:

Value v = fooV();

Otherwise, if you need a function that modifies a Value struct that you already have, you have two options: you either need to change the return type of fooV:

Value fooV(Value v){
    v.id = 10;
    v.type = 'L';
    v.a = 'R';
    return v;
}

in which case you would call it like:

v = fooV(v);

or change fooV to accept a pointer to a Value:

void fooV(Value* v){
    v->id = 10;
    v->type = 'L';
    v->a = 'R';
}

in which case you would call it like:

fooV(&v);

Upvotes: 5

pascal
pascal

Reputation: 3365

And change the second printf to use the values of v, not the variable id, type, a.

printf("id: %d, type: %c, a: %c \n",v.id,v.type,v.a);

Upvotes: 1

aib
aib

Reputation: 47001

You need to pass v in by reference, which is done using pointers in C:

void fooV(Value* v)
{
    (*v).id = 10;
    (*v).type = 'L';
    (*v).a = 'R';
}

Or use the -> shorthand operator:

void fooV(Value* v)
{
    v->id = 10;
    v->type = 'L';
    v->a = 'R';
}

And don't forget to pass v's address:

fooV(&v);

Upvotes: 9

Related Questions