Reputation: 15
I want the address of structure, but in my code I am only able to return the address of value the first member. Can I typecast the address of value to struct classifier? If yes how to type cast it ? For example, my function only returns the address of value
in the below mentioned struct
can I cast this address to classifier
?
struct classifier
{
int value;
struct packet_filter pktFltr;
struct classifier *next;
}
Upvotes: 1
Views: 149
Reputation: 108988
If you have an object of type struct classifier
, the address of that object is of type struct classifier *
. There is nothing special about it ...
#include <stdio.h>
struct classifier {
int value;
struct packet_filter pktFltr;
struct classifier *next;
};
void foo(struct classifier *bar) {
printf("value is %d\n", bar->value);
}
int main(void) {
struct classifier example = {42}; /* value is 42, everything else is 0 */
foo(&example); /* ok, `&example` is of the correct type */
return 0;
}
Upvotes: 0
Reputation: 59461
While it is guaranteed that the first member of struct will have the same address as struct itself (as padding is not permitted in the beginning), casting the return value of an int* function()
to some_struct*
is not a good practice - what if someone later decides to modify the function to return the address of some malloc'ed int instead?
Upvotes: 0
Reputation: 15849
The standard states that the address of a structure classifier
is the same as the address of its first member value
provided that you are casting it correctly.
That is, following is equivalent, p points to the same address :
int *p;
struct classifier c;
p = (int*)c;
p = &c.value;
Meaning that
(int*) c == &c.value
And in your case, if I understand it correctly you would want:
c = (struct chassifier *) adress_of_my_first_member_in_struct_classifier;
Upvotes: 1