Reputation: 131
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
?
Upvotes: 1
Views: 305
Reputation: 4220
You can create a pointer to another struct like below,
#include<stdio.h>
struct emp_1 {
int id;
char *name;
};
struct company {
int id;
char *name;
struct emp_1 emp;
};
void main(void)
{
struct company company;
struct emp_1 *emp = (struct emp_1 *)&company;
company.id = 100;
company.name = "Payoda";
emp -> id = 100;
emp -> name = "Mohanraj";
printf("emp id is : %d \n", emp -> id);
printf("emp name is : %s \n", emp -> name);
}
Upvotes: -1
Reputation: 320699
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?
Upvotes: 4
Reputation: 12515
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?
Upvotes: 1
Reputation: 10392
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.
Upvotes: 0