0

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.

1
  • 1
    Brackets are not necessary. -> has a higher precedence than &. Commented Jan 10, 2015 at 21:57

4 Answers 4

4

Just use the & address of operator, like this

Other_Struct **ptrptr = &(abcd->ptr);
Sign up to request clarification or add additional context in comments.

Comments

3

How about this:

&(abcd->ptr)

Comments

2

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().

3 Comments

%p is defined for void-pointers only. So it shall be printf("%p %p\n", (void*) abcd, (void*) &abcd->ptr);
Right, because the size of a pointer can be different depending of what's being pointed to in some platforms. (Typically between code and data -- is there a platform where it varies between different types of data? I thought the void pointer definition was there to prevent usage with void(*)(), and usage such as the one above could be considered safe.)
"is there a platform where it varies between different types of data" at least there were, if still in use, I do not know. However, to stick to the Standard my comment stands as is.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.