-1

当我在 C 中编译我的代码时,我收到以下错误“错误 LNK2001:未解析的外部符号_staff”以及有关未解析的外部的错误。听起来它认为我的人员数组需要一个外部文件,但它只是一个用于保存 Persons 的数组(两种类型的联合)。我该如何解决这个问题?我的代码的开头如下。

        #include <stdio.h>
        #include <string.h>
    //employee struct

        typedef struct {    
        //...
        } Employee;

    //Manager struct inheriting from employee struct

        typedef struct {
        Employee employee;   
        int bonus;
        } Manager;  

    //union of manager and employee

        typedef union{
           Employee e;
           Manager m;
          } Person;
    //functions

        Employee newEmployee(char n[], ...);    
        Manager newManager(...);
        double getManagerSalary(Manager man);    
        Manager boss; 
        Employee harry ;
        Employee tommy;
        Person staff[];

//main code

    int main(void)
    {

      boss = newManager(...);
      harry = newEmployee(...);       
      tommy = newEmployee(...);

      staff[3]; 
      staff[0].m = boss;
      staff[1].e = harry;
      staff[2].e = tommy;

     ...    
    }   

    Employee newEmployee(char n[], double s, int year, int month, int day)
    {
    ...
    }
4

2 回答 2

1

必须在 C 中声明数组才能具有大小,例如:Person a[1]这意味着a is an array of 1 Person. 您不能以您所做的方式声明它。

如果您想估计运行时的人数,请尝试指针。然后考虑总人数并继续分配内存但我认为你Person *a不想这样做。

另请参阅extern@ShinTakezou 的消息。尽管与您的实施完全无关,但这是一个重要且有效的观点。

于 2012-05-15T05:14:47.487 回答
0
        // you are not reserving room for anything;
        // gcc would give an error; your compiler silently consider this
        // staff as a pointer to something (an array) which has its actual
        // memory defined elsewhere; so, when you link, it raises that 
        // linking error
        Person staff[];

        // could be
        Person staff[N];
        // where N is a positive number, or a true define or const value

//main code

    int main(void)
    {

      boss = newManager(...);
      harry = newEmployee(...);       
      tommy = newEmployee(...);

      // the following line is an expresion which does nothing:
      // it accesses the fourth element of a "supposed" array,
      // and the value retrieved in this way is lost
      // if you meant to "allocate" three staff, you are doing it wrong; 
      staff[3]; 

      // following the possible previous path of having the 
      // room for staff not dynamically created, you don't need the
      // previous line, which is simply a no-op (if 3 is less than N-1, 
      // otherwise it's a potentially illegal access to memory you shouldn't access)

      staff[0].m = boss;
      staff[1].e = harry;
      staff[2].e = tommy;

     ...    
    }   

(我还补充说,代码看起来并不完全“理智”——不用说也许——对我来说,但这可能是另一个问题的问题,与这个特定问题无关)

于 2012-05-15T17:02:09.820 回答