简体   繁体   English

指向C中的结构字段的指针

[英]Pointer to pointer of struct field in C

I have: 我有:

typedef struct
{
    int id;
    Other_Struct *ptr;
} My_Struct;

Lets say I have the pointer abcd which its type is My_Struct . 可以说我有指针abcd ,其类型为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 . 我的意思是ptr本身的地址(例如指向指针的指针),而不是存储在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). 如果我理解正确,在这种情况下,您有My_Struct *abcd指向一个地址,而您想要的是此结构内部字段的地址(该字段是否是指针都没有关系)。 The field is abcd->ptr , so its address you want is &abcd->ptr . 该字段是abcd->ptr ,因此您想要的地址是&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 ): 您可以通过打印实际的指针值(地址之间的差应为My_Struct内的ptr偏移量)轻松检查此情况:

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. 更新:如果您想让代码具有可移植性,符合标准并能证明过去和未来,请按照以下@alk的注释,将对void *强制转换添加到printf()参数中。 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() . 为了正确起见,您还可以使用标准的入口点原型( int main(void)int main(int argc, char **argv) ),当然也可以包括stdio.h来使用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. 我不知道括号是否真的必要,而且我也不在乎,因为反正这样更易读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM