tags:

views:

142

answers:

3

I have a struct defined with the structure as follows (names are different)

struct str1
{
   int field1;
   struct str2;
}

And I have a *str1 in a function. I'd like to get a pointer to str2.

So I tried &(str1->str2) and was hoping this would return a pointer to str2. Is this incorrect? It doesn't seem to be working. How would I get a pointer to str2 if given a pointer to str1?

A: 

If you have a pointer to str1, you may need to do:

&(*(str1).str2)

not really sure about this, but try it, I do not have a C compiler at hand.

Francisco Soto
LukeN
+2  A: 

If p is a ponter to an object of struct str1 type, then &p->str2 will give your the pointer to its str2 member (assuming it has str2 member).

"Doesn't seem to be working" is not a meaningfull description of a problem. Your examples look suspicious though. The struct str2 inside struct str1 makes no sense. What is it supposed to be? A forward declaration of a struct type? And is your pointer really named str1? Same as the struct tag?

AndreyT
+1  A: 

Your solution should be correct. str1->str2 points you to the struct and taking its address whould get you a pointer to that value.

What is your debugger telling you? Perhaps your str1 pointer is garbage?

Michael Dorgan