c中的动态位置不工作
如果每次尝试运行案例1时分配中出现错误,我将退出1。我不知道为什么,我能得到一些帮助吗c中的动态位置不工作,c,pointers,structure,allocation,C,Pointers,Structure,Allocation,如果每次尝试运行案例1时分配中出现错误,我将退出1。我不知道为什么,我能得到一些帮助吗 #include <stdio.h> #include <stdlib.h> typedef struct hospede{ //guest int numreg; //register num char nome[80]; int acompanhante; //n of ppl int dias; //tim
#include <stdio.h>
#include <stdlib.h>
typedef struct hospede{ //guest
int numreg; //register num
char nome[80];
int acompanhante; //n of ppl
int dias; //time to stay
estado tabela;
}hospede;
typedef struct quarto{ //room
int num; //num do quarto
char categoria; //[S] ou [F]
char status; //[L] ou [O]
estado stats;
}quarto;
void alocaHospede(hospede **hosp, int tam);
void alocaQuartos(quarto **quar, int tam);
void geraQuartos(quarto *quar);
void checkIn(hospede *hosp, int tam);
int main()
{
hospede *hpd = NULL;
quarto *qrt = NULL;
quarto quart;
int qtd = 0;
char op;
int x;
qrt = &quart;
geraQuartos(qrt);
do{
printf("\n1-CheckIn\n>");
scanf("%i", &x);
fflush(stdin);
switch(x){
case 1:
alocaHospede(&hpd, qtd+1);
checkIn(hpd, qtd);
}
printf("\nDeseja continuar? \n");
scanf("%c", &op);
fflush(stdin);
}while(op!='n' && op!='N');
return 0;
}
void checkIn(hospede *hosp, int tam){
printf("\nwork\n");
}//checkIn
void alocaHospede(hospede **hosp, int tam){
*hosp = (hospede*)realloc(*hosp, tam*sizeof(hospede));
if(*hosp == NULL)
exit(1);
}//aloca hospede
void alocaQuartos(quarto **quar, int tam){
if((*quar = (quarto *) realloc(*quar, tam * sizeof(quarto)))== NULL)
exit(1);
}//alocaQuartos
void geraQuartos(quarto *quar){
int i;
for(i=0;i<15;i++,quar++){
(*quar).num = i+1;
}
}//geraQuartos
OBS:
我删除了一些尚未使用的结构和联合,以缩短代码,我还将分配到房间,我认为这是相同的问题。geraQuartosqrt导致堆栈溢出,因为quart只有1个条目长度,但您在函数中写入了第1到第15个条目。 堆栈溢出可能会发生任何奇怪的情况。geraQuartos中的for循环将其参数视为指向15个quartos结构数组的指针。但它只是一个指向一个结构的指针,所以它写在对象的边界之外。这会导致未定义的行为,在这种情况下,它会覆盖hpd,所以它不是空的。这会导致realloc失败,因为第一个参数不是NULL或malloc以前返回的指针 将夸脱声明更改为: 然后做:
geraQuartos(quart);
geraQuartos(quart);