Simple Question on Pointers
Can someone remind me why this works?
A function requiring int* could take as input an (obviously)
int *integer;
but it could also accept
&var->integer
with var being var_t*, where var_t:
typedef struct {
int integer;
} var_t;
why is the 2nd accepted?
edit: oopsy, question is same but var is actually a var_t* (and not a var_t) to be more prec开发者_JAVA百科ise.
Let's break it down.
var
is a var_t*
.
var->integer
is an int
.
&var->integer
is an int*
.
The second version is accepted because of the ampersand at the beginning. This means that the address of the field is passed, not the actual value.
If the type of var is var_t
, the code you've shown is actually illegal. If its type is var_t*
, it's accepted because the type of var->integer
is int
and the type of &some_int
is int*
.
2nd version of code is only good version, because you must use & operator to get address of integer in var_t structure.
Do the math your self:
int a => &a is of type int*
int *a => &a is of type int**
int **a => &a is of type int***
etc.
int *a => *a is of type int
int **a => a is of type int**
int **a => *a is of type int*
int **a => **a is of type int
精彩评论