在其他结构中使用结构。C

在其他结构中使用结构。C,c,struct,structure,typedef,C,Struct,Structure,Typedef,我在一个.h文件中有三个结构 typedef struct name{ char first[20]; char middle; char last[20]; } PersonName; typedef struct address{ char street[20]; char city[20]; char state[20]; int zipCode; } PersonAddress;

我在一个.h文件中有三个结构

typedef struct name{
      char first[20];
      char middle;
      char last[20];
    } PersonName;

typedef struct address{
      char street[20];
      char city[20];
      char state[20];
      int zipCode;
        } PersonAddress;

typedef struct employee{
      PersonName bob;
      PersonAddress place;
      int id;
    } Employee;
我想做的是用员工结构来做其他结构的工作

我有个电话:

     void setName(struct employee* object, char* f, char* l, char* m);
到my.c文件,该文件应在以下位置接收:

 void setName(struct employee* object, char* f, char* l, char* m){
        strncpy(object.bob.first,f,20);
        strncpy(object.bob.last,l, 20);
        object.bob.middle=m[0];

    }
能够在不使用其他结构的情况下更改值。我只是看错了吗?CMD说“在非结构中请求bob。
任何帮助都将不胜感激。

对象是指针,因此您需要键入object->bob来访问bob。 bob是一个结构,所以需要object->bob.first才能首先访问


此外,在需要更改之前,您可能希望将所有这20个变量替换为一个常量,忘记更改其中一个,并且到处都是bug。

Bob是指针。要访问其成员,请尝试使用->操作符而不是

换言之:

void setName(struct employee* object, char* f, char* l, char* m){
  strncpy(object->bob.first,f,20);
  strncpy(object->bob.last,l, 20);
  object->bob.middle=m[0];
}

object
是指向结构的指针,而不是结构本身。因此,您需要使用
->
来访问成员,而不是
。object是指向结构的指针。请改为使用object->bob。啊,好的!非常感谢!!这解决了我的问题。您可能需要使用sizeof表达式,而不是使用literal常量。这将允许您的代码自动跟踪结构定义中的更改