简体   繁体   中英

Accessing a struct within a struct

If I have something like:

struct foo {
    struct bar {
         char name[8];
         int temp;
    } example[100];
};

If I wanted to get what name is, how would I do so for say the first element in the array?

#include <stdio.h>

struct foo {
    struct bar {
         char name[8];
         int temp;
    } example[100];
};


int main(void) {
  struct foo my_foo;
  printf("%s\n", my_foo.example[0].name);
  return 0;
}

I didn't check if your code compiles, but that would be something like:

foo var;
var.example[0].name
struct foo myfoo;
char * the_name;

/* initialize myfoo ... */

the_name = myfoo.example[0].name;
struct foo var;
printf("name -- %s\n", var.example[0].name);

NOTE : i advice you to abbreviate your strcut like this :

typedef struct foo foo;
struct foo {
    struct bar {
         char name[8];
         int temp;
    } example[100];
};

like this you will not be obliged to declare your vars like this :

struct foo var;

but

foo var;

Good luck ;

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