gpt4 book ai didi

C 编程结构体运行时错误

转载 作者:行者123 更新时间:2023-11-30 15:20:20 25 4
gpt4 key购买 nike

createStructs() 中注释掉的行给了我有问题的错误。我试图从文本文件中扫描信息列表,但加载文件后程序崩溃。当它崩溃时,它会加载输出,但以一种非常奇怪的方式。这是我的代码:

#define MAX 71
#define SIZE 14

typedef struct {
char first[7];
char initial[1];
char last[9];
char street[16];
char city[11];
char state[2];
int zipcode[5];
int age;
char sex[1];
int tenure;
double salary;
} Employee;
insert main method just calling the functions
void strsub(char buf[], char sub[], int start, int end) {
int i, j = 0;

for (j = 0, i = start; i <= end; i++, j++) {
sub[j] = buf[i];
}
sub[j] = '\0';
}

void createStructs(Employee inWorkers[]) {
int i = 0;
char buf[MAX];
char temp[SIZE];
if (!(fp = fopen("payfile.txt", "r"))) {
printf("payfile.txt could not be opened for input.");
exit(1);
}

while (!(feof(fp))) {
fgets(buf, MAX, fp);
strsub(buf, inWorkers[i].first, 0, 6);
strsub(buf, inWorkers[i].initial, 8, 8);
strsub(buf, inWorkers[i].last, 10, 18);
strsub(buf, inWorkers[i].street, 20, 35);
strsub(buf, inWorkers[i].city, 37, 47);
strsub(buf, inWorkers[i].state, 49, 50);
strsub(buf, temp, 52, 56);
//inWorkers[i].zipcode = atoi(temp);
strsub(buf, temp, 58, 59);
inWorkers[i].age = atoi(temp);
strsub(buf, inWorkers[i].sex, 61, 61);
strsub(buf, temp, 63, 63);
inWorkers[i].tenure = atoi(temp);
strsub(buf, temp, 65, 70);
inWorkers[i].salary = atof(temp);
i++;
}
}

void printNames(Employee workers[]) {
for (int i = 0; i < SIZE; i++) {
printf("%s %s %s %s %s %s %d %d %s %d %.2lf", workers[i].first, workers[i].initial, workers[i].last,
workers[i].street, workers[i].city, workers[i].state, workers[i].zipcode, workers[i].age,
workers[i].sex, workers[i].tenure, workers[i].salary);
}
}

最佳答案

您的问题是您正在创建一个整数数组 (int zipcode[5])。然后,您尝试将 atoi 调用的结果传递给 inworkers[i].zipcode。这会导致您将一个整数值分配给一个整数指针。

如果您在编译时没有收到警告,我会感到非常惊讶。作为第一步,您确实应该使用 -Wall 进行编译并解决所有警告。

与其创建一个整数数组,为什么不直接让它成为一个整数值呢?

关于C 编程结构体运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30066027/

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