2

运行 prog.c 时出现分段错误。我发现它与我的 *char 相关。这是代码。

程序.c

#include <stdio.h>
#include "worker.h"
#include "manager.h"
#include "employee.h"

int main(int argc, char **argv) {
  int i;
  Worker boss = (Worker) new_Manager("Carl Cracker", 80000, 1987, 12, 15);
  return 0;       
}

工人.h

#ifndef _WORKER_H_
#define _WORKER_H_

 #define WORKER   char *name;   \
          double salary;    \
          long hireDay; \
          void (*raiseSalary)(Worker this, double byPercent);   

typedef struct Worker_struct* Worker;
struct Worker_struct {
   WORKER;
} Worker_struct;

void raiseSalary(Worker this, double byPercent);

#endif

工人.c

#include <stdio.h>
#include <stdlib.h>

#include "worker.h"

void raiseSalary(Worker this, double byPercent) {
  Worker worker = (Worker) this; 
  printf("worker_c: raising salary\n");
  double raise = worker->salary * byPercent / 100;
  worker->salary = worker->salary + raise;
}

经理.h

#ifndef _MANAGER_H_
#define _MANAGER_H_

#include "worker.h"


typedef struct Manager_struct* Manager;
struct Manager_struct {
  WORKER;
  double bonus;
void (*setBonus)(Worker this, double b);
} Manager_struct;

Manager new_Manager(char *name, double salary, int year, int month, int day);
#endif

经理.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include "manager.h"

static void setBonus(Worker this, double b) {
  Manager manager = (Manager) this; 
  manager->bonus = b;
}

Manager new_Manager (char *name, double salary, int year, int month, int day) {
  Manager manager;
  strcpy (manager->name, name);//----i think my problem is here----
 manager->salary = salary;
 manager->bonus = 0;    
 manager->setBonus = setBonus;
 manager->raiseSalary = raiseSalary;

return manager;
}

我认为我的问题出在 strcpy 的 manager.c 中。我究竟做错了什么?

4

1 回答 1

2

您已char *nameWORKER宏中声明,但尚未为其分配内存。

请不要像这样在宏中定义变量;绝对没有任何好处,并且不必要地使代码复杂化。直接在Worker_struct.

于 2012-05-11T02:02:47.250 回答