gpt4 book ai didi

c - 字符段错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:08 26 4
gpt4 key购买 nike

我在运行 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;
}

worker .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

worker .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 中。我做错了什么?

最佳答案

您已在 WORKER 宏中声明了 char *name,但尚未为其分配内存。

拜托,请不要像这样在宏中定义变量;绝对没有任何好处,而且不必要地使代码复杂化。只需在 Worker_struct 中直接定义它们即可。

关于c - 字符段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10544441/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com