简体   繁体   English

访问结构中的结构

[英]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? 如果我想知道name是什么,该如何说数组中的第一个元素?

#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 : 注意:我建议您这样缩写您的strcut:

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 : 这样,您将不必像这样声明您的var:

struct foo var;

but

foo var;

Good luck ; 祝好运 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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