Reputation: 3
I am trying to pass a member of a stuct to a function in c by reference and then use it to access the same member of a struct of the same type.
typedef struct Node
{
int a;
int b;
int c;
} Node;
Node mynode; //global
void pass_member(int *member){
mynode.&member = 1;//gives a compiler error
}
void main()
{
mynode.a = 0;
mynode.b = 45;
mynode.c = 64;
pass_member(&mynode.a)
}
I can see that mynode.&member
is not allowed in c but i think it shows what i am trying to do
is it possible to pass the address of an member of a struct to a function in c
and then use it to access that member in a struct of the same type?
basically what i am trying to achieve is a function somthing like this
void set_member(int value_to_set, int * pointer_to_member_of_which_to_set);
that would set a specific member of a global struct depending on the given member to the function.
Upvotes: 0
Views: 1121
Reputation: 11513
You can use offsetof
to get the relative address of a member. I am unaware of a reverse operation (don't do much in C), but it can be simulated like this:
#define offsetin(s,a,t) *((t*)(((char*)&s)+a))
Then your code would look like this:
void pass_member(size_t member){
offsetin(mynode, member, int) = 1;
}
void main()
{
mynode.a = 0;
mynode.b = 45;
mynode.c = 64;
pass_member(offsetof(Node,a));
}
Upvotes: 0
Reputation: 30926
I will give you some example first:-
You can do it like this func(&mynode)
.
And func
is void func(Node* aa)
Now you can use it like this
aa->a = aa->a + 1
etc.
Most of the time you will send the address of the whole structure rather than the address of the individiual element.
Node aa
=> aa is of type struct node (typedefed to Node)
It's address: &aa
aa.a
is the element of the structure aa
and it's address is &aa.a
void pass_member(int *member){ *member = 1; }
pass_member(&mynode.a) // in main()
Also you can use it like this:-
typedef struct Node
{
int a;
int b;
int c;
} Node;
Node mynode; //global
void pass_member(Node *member){
(*member).a = 1;//member->a = 1
}
void main()
{
mynode.a = 0;
mynode.b = 45;
mynode.c = 64;
pass_member(&mynode)
}
You asked is it possible to pass the address of an member of a struct to a function in c?
Ans: Yes it is possible, it is shown in the answer.
and then use it to access that member in a struct of the same type?
You can access that memebr be it of some struct or some other struct. As long as it is a pointer to an appropriate type it's possible.
Upvotes: 1
Reputation: 7542
You have two options, either pass pointer to the member variable as
void pass_member(int *member){
*member = 1;
and
pass_member(&mynode.a);
OR pass pointer to the entire structure
void pass_member(Node *member){
(*member).a = 1; //or member->a = 1; as pointed out in comments
and
pass_member(&mynode)
Upvotes: 0