Reputation: 3415
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
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
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
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