gpt4 book ai didi

c - C程序运行时出现段错误

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

我试过 malloc,但没有 malloc,它会构建但不会运行或编译。当我在 codepad.org 上运行代码时,出现段错误。我输入了一系列结构,我正在通过它们搜索特定项目。据我所知,没有编译。代码如下(我用的是netbeans、codeblocks、visual basic 2012程序):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
#define BLOODTYPESIZE 4
#define MAX 120000

typedef struct {
int month;
int day;
int year;
} dateT;

typedef struct {
int hour;
int minute;
} timeT;

typedef struct {
char name[SIZE];
char organname[SIZE];
char bloodtype[BLOODTYPESIZE];
dateT dateAdded;
timeT timeAdded;
int received;
} organT;

int main(void) {
int i, n, k, j;
int c;
int *ptr;

char organ[SIZE];
char bloodkind[BLOODTYPESIZE];

organT patient[MAX];

scanf("%d",&n);
ptr = (int *)malloc(n * sizeof(*ptr));
printf("Enter patient information\n");
for(i=1; i<=n; i++){
scanf("%s", patient[i].name[SIZE]);
scanf("%s", patient[i].organname[SIZE]);
scanf("%s", patient[i].bloodtype[BLOODTYPESIZE]);
scanf("%d %d %d", patient[i].dateAdded);
scanf("%d %d", patient[i].timeAdded);
patient[i].received = 0;
}
scanf("%d", &k);
for(j=0; j<k; j++) {
gets(organ);
printf("Organ received: %s", organ);
gets(bloodkind);
printf("Organ has blood type: %s", bloodkind);
}
for (c=0; c<n; c++){
if(patient[i].organname == organ){
if(patient[i].bloodtype == bloodkind){
if(patient[i].received == 0) {
printf("Patient(s) Found!\n");
printf("%s", patient[i].name[SIZE]);
printf("Organ received: %s", organ);
patient[i].received = 1;
}
if(patient[i].received == 1)
printf("Patient already received organ\n");
}
else("Not correct blood type\n");
}
else("No match found\n");
}

return (EXIT_SUCCESS);
}

最佳答案

您似乎没有正确使用地址。例如,当你说

scanf("%s", &patient[i].name[SIZE]);

您实际上正在阅读为 patient[i].name 分配的空间。您应该将语句更改为

scanf("%s",patient[i].name);

并以类似的方式修复其他语句。

关于c - C程序运行时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18707368/

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