can address be typecasted?
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 addre开发者_如何学运维ss 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;
}
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;
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?
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;
}
精彩评论