简体   繁体   中英

C Pointer Question: &(*struct->struct)

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 ?

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?

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?

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.

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);
}

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.

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