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
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With