Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return values from a struct

Tags:

c

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

like image 409
user133466 Avatar asked Sep 15 '26 08:09

user133466


2 Answers

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);
like image 153
aib Avatar answered Sep 18 '26 00:09

aib


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);
like image 22
James McNellis Avatar answered Sep 18 '26 00:09

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!