I have:
typedef struct
{
int id;
Other_Struct *ptr;
} My_Struct;
Lets say I have the pointer abcd
which its type is My_Struct
.
How can I get the address of:
abcd->ptr
?
I mean the address of ptr
itself (like pointer to pointer) and not the address which is stored in ptr
.
只需使用运算符的&
地址,就像这样
Other_Struct **ptrptr = &(abcd->ptr);
这个怎么样:
&(abcd->ptr)
If I understood correctly, in this scenario you have My_Struct *abcd
pointing to an address, and what you want is the address of a field inside this structure (it doesn't matter if this field is a pointer or not). The field is abcd->ptr
, so its address you want is &abcd->ptr
.
You can easily check this by printing the actual pointer values (the difference between the addresses should give you the offset of ptr
inside My_Struct
):
struct My_Struct {
int id;
void *ptr;
};
main()
{
struct My_Struct *abcd;
printf("%p %p\n", abcd, &abcd->ptr);
}
Update: If you want your code to be portable, standards-compliant, and past and future proof, you may want to add casts to void *
to the printf()
arguments, as per @alk's comments below. For correctness, you can also use a standard entry point prototype ( int main(void)
or int main(int argc, char **argv)
) and, of course, include stdio.h
to use printf()
.
The most unambiguous way to do it is thus:
My_Struct *abcd;
Other_Struct **pptr;
pptr = &(abcd->ptr);
I don't know if the parentheses are really necessary, and I don't care, because it's more readable this way anyway.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.