tags:

views:

100

answers:

3
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

+5  A: 

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);
James McNellis
+7  A: 

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);
aib
As an alternative, you could return a `Value` struct from `fooV()`: `Value fooV(Value v);` though it's probably less efficient.
Chris Lutz
I got it to work!!!!but would you explain the difference between (*v).id = 10; and *(v).id = 10; for some reason, i think they are the same...
@metashockwave: The operator "." has higher precedence than the operator "*", so "*(v).id" and "*v.id" will both be interpreted as "*(v.id)". To get the intended meaning, that is to FIRST follow the pointer using "*", and THEN to get the "id" field in the struct, you need to write "(*v).id" or "v->id".
Thomas Padron-McCarthy
+1  A: 

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);
pascal