代码之家  ›  专栏  ›  技术社区  ›  AKon

C函数使用structs,为什么它不起作用?

  •  0
  • AKon  · 技术社区  · 12 年前

    我在这个实现中遇到了很多错误。

    typedef struct EmployeeStruct
    {
        char lastName[MAX_LENGTH];
        char firstName[MAX_LENGTH];
        int employeeNumber;  // Holds the employee's ID. This value is
                                 // equal to the number of employees
        struct EmployeeStruct *Next;  // Pointer to the next most recently hired Employee
    }Employee;
    

    当试图创建一个将返回指向此结构的指针的函数时,就会出现问题。错误出现在malloc调用中,导致“new”没有被正确声明,因此该函数中的所有行都有错误。

    Employee* hireEmployee(Employee tail, char lastName[MAX_LENGTH], char firstName[MAX_LENGTH])
    {
        struct Employee *new = (Employee*)malloc(sizeof(Employee));
        new.lastName = lastName;
        new.firstName = firstName;
        new.next = tail;
        tail.next = new;
        new.employeeNumber = employeeCount;
    
        return tail;
    }
    

    这是一个错误列表。谢谢你的帮助!

    lab6.c:19: warning: initialization from incompatible pointer type
    lab6.c:20: error: request for member ‘lastName’ in something not a structure or union
    lab6.c:21: error: request for member ‘firstName’ in something not a structure or union
    lab6.c:22: error: request for member ‘next’ in something not a structure or union
    lab6.c:23: error: ‘Employee’ has no member named ‘next’
    lab6.c:24: error: request for member ‘employeeNumber’ in something not a structure or union
    lab6.c:26: error: incompatible types in return
    
    2 回复  |  直到 12 年前
        1
  •  4
  •   simonc    12 年前

    这里有几个不同的问题:

    您需要使用指针取消引用运算符 -> 访问指向结构的指针的成员。
    然后您需要使用 strcpy 分配给您的 char 阵列。
    您需要避免链接列表中出现循环(您正在设置 new tail 相互指向 next ). 显而易见的解决办法是 成为新的 。调用代码可能需要更新以反映这一点。
    最后,您不应该从 malloc
    真的最后, 下一个 应该是 Next 。或者您可以更改结构定义中的大小写。

    Employee *new = malloc(sizeof(Employee));
    strcpy(new->lastName, lastName);
    strcpy(new->firstName, firstName);
    new->Next = NULL;
    tail->Next = new;
    new->employeeNumber = employeeCount;
    
        2
  •  0
  •   Neeraj Kumar    12 年前

    这里有几件事。
    1) Employee已经是typedef,所以不需要在malloc语句中使用struct。
    2) new是指向结构的指针。因此,通过指针访问结构的对象的方法是StructPointer->StructObject或*(StructPointer).StructObject
    3) 我看到您试图将tail分配给next,但将tail作为结构对象传递。它必须是一个结构指针。 4) 您应该使用strcpy来复制字符数组。