简体   繁体   English

访问嵌套体中内部结构的元素

[英]access elements of inner structure in a nested body

Can we not access the elements of inner structure?(which is dept in this case). 我们可以不访问内部结构的元素吗?(在这种情况下是部门 )。

When i try to initialize the value of dept structure, i get errors mentioned in the last. 当我尝试初始化dept结构的值时,我得到了最后提到的错误。

#include <stdio.h>
#include <string.h>
struct employe
{
    char name[10];
    int i;
    struct dept
    {
        char name[10];
        int uniq_num;
    }d;
}e;
int main()
{
strcpy(d.name, "CS");
strcpy(e.d.name, "Computer Science");
printf("The dept name: %s \n", d.name);
printf("Employee dept name: %s \n", e.d.name);
getchar();
return 0;
}

Errors - 错误 -

"example9.c", line 18: undefined symbol: d
"example9.c", line 18: warning: left operand of "." must be struct/union object
"example9.c", line 18: cannot access member of non-struct/union object
"example9.c", line 20: warning: left operand of "." must be struct/union object
"example9.c", line 20: cannot access member of non-struct/union object

You have (by mistake?) used d.name instead of e.name in eg the first strcpy call. 您(错误地?)在例如第一次strcpy调用中使用了d.name而不是e.name

You use the correct syntax to access the nested structure in one strcpy and printf call, when you do edname . 当您执行edname时,可以使用正确的语法在一次strcpyprintf调用中访问嵌套结构。

As I mentioned, You cannot access inner elements without using object/pointer of/to structure. 正如我所提到的,如果不使用/ to结构的对象/指针,则无法访问内部元素。 just like to access name variable, you have to use e.name, similarly to access d variable, you must have to use ed 就像访问name变量一样,你必须使用e.name,类似于访问d变量,你必须要使用ed

It's better to define the structures separately: 最好分别定义结构:

struct dept
{
    char name[10];
    int uniq_num;
};

struct employe
{
    char name[10];
    int i;
    struct dept d;
}e;

and then you can access the d members of e structure with edname, eduniq_num. 然后你可以用edname,eduniq_num访问e结构的d个成员。

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

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